﻿using System;
using System.IO;
using System.Web.Configuration;
using System.Web.Mvc;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.WxOpen.Entities.Request;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.MP.Sample.CommonService.TemplateMessage.WxOpen;
using Senparc.Weixin.MP.Sample.CommonService.WxOpenMessageHandler;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;
using Senparc.Weixin.WxOpen.Entities;
using Senparc.Weixin.WxOpen.Helpers;
using Senparc.Weixin;
using Senparc.Weixin.MP;

using System.Collections.Generic;
using Dos.Common;
using Dos.ORM;
using Business;
using Model;
using Common;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;

namespace wxkq.Controllers
{
    /// <summary>
    /// 微信小程序Controller
    /// </summary>
    public partial class WxOpenController : CommonController
    {
        #region 小程序基础内容不用改


        public static readonly string Token = WebConfigurationManager.AppSettings["WxOpenToken"];//与微信公众账号后台的Token设置保持一致，区分大小写。
        public static readonly string EncodingAESKey = WebConfigurationManager.AppSettings["WxOpenEncodingAESKey"];//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string AppId = WebConfigurationManager.AppSettings["WxOpenAppId"];//与微信小程序账号后台的AppId设置保持一致，区分大小写。
        public static readonly string AppSecret = WebConfigurationManager.AppSettings["WxOpenAppSecret"];//与微信小程序账号后台的AppId设置保持一致，区分大小写。

        readonly Func<string> _getRandomFileName = () => DateTime.Now.ToString("yyyyMMdd-HHmmss") + Guid.NewGuid().ToString("n").Substring(0, 6);

        /// <summary>
        /// GET请求用于处理微信小程序后台的URL验证
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Index")]
        public ActionResult Get(PostModel postModel, string echostr)
        {
            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content(echostr); //返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed:" + postModel.Signature + "," + CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
                    "如果你在浏览器中看到这句话，说明此地址可以被作为微信小程序后台的Url，请注意保持Token一致。");
            }
        }

        /// <summary>
        /// 用户发送消息后，微信平台自动Post一个请求到这里，并等待响应XML。
        /// </summary>
        [HttpPost]
        [ActionName("Index")]
        public ActionResult Post(PostModel postModel)
        {

            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content("参数错误！");
            }

            postModel.Token = Token;//根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
            postModel.AppId = AppId;//根据自己后台的设置保持一致

            //v4.2.2之后的版本，可以设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
            var maxRecordCount = 10;


            //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
            var messageHandler = new CustomWxOpenMessageHandler(Request.InputStream, postModel, maxRecordCount);

            try
            {
                return Content("");
            }
            catch (Exception ex)
            {
                return Content("");
            }
        }

        /// <summary>
        /// wx.login登陆成功之后发送的请求
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OnLogin()
        {
            string code = Assiweb.GetRequestString("code");
            var jsonResult = SnsApi.JsCode2Json(AppId, AppSecret, code);
            if (jsonResult.errcode == ReturnCode.请求成功)
            {
                //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息（不推荐）
                //使用SessionContainer管理登录信息（推荐）

                var key = SessionHelper.GetNewThirdSessionName();

                var sessionBag = new Senparc.Weixin.WxOpen.Containers.SessionBag()
                {
                    Key = key,
                    OpenId = jsonResult.openid,
                    UnionId = jsonResult.unionid,
                    SessionKey = jsonResult.session_key,
                    ExpireTime = DateTime.Now.Add(TimeSpan.FromDays(365))
                };

                SessionContainer.Update(key, sessionBag, TimeSpan.FromDays(365));
                
                //var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key,jsonResult.unionid);

                //注意：生产环境下SessionKey属于敏感信息，不能进行传输！
                return Json(new Jr(new { sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey }));
            }
            else
            {
                return Json(new Jr(false, jsonResult.errmsg));
            }
        }

        [HttpPost]
        public ActionResult CheckWxOpenSignature(string sessionId, string rawData, string signature)
        {

            try
            {
                var checkSuccess = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.CheckSignature(sessionId, rawData, signature);
                return Json(new { success = checkSuccess, msg = checkSuccess ? "签名校验成功" : "签名校验失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult DecodeEncryptedData()
        {
            string type = Assiweb.GetRequestString("type");
            string sessionId = Assiweb.GetRequestString("sessionId");
            string encryptedData = Assiweb.GetRequestString("encryptedData");
            string iv = Assiweb.GetRequestString("iv");

            DecodeEntityBase decodedEntity = null;
            switch (type.ToUpper())
            {
                case "USERINFO"://wx.getUserInfo()
                    decodedEntity = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeUserInfoBySessionId(
                        sessionId,
                        encryptedData, iv);
                    //判断用户是否存在,不存在则更新数据库
                    break;
                //case "COMMON"://wx.common()
                //    re = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedDataBySessionId(sessionId, encryptedData, iv);
                //    break;
                default:
                    break;
            }

            return Json(new Jr(decodedEntity));

            ////检验水印
            //var checkWartmark = false;
            //if (decodedEntity != null)
            //{
            //    checkWartmark = decodedEntity.CheckWatermark(AppId);
            //}

            ////注意：此处仅为演示，敏感信息请勿传递到客户端！
            //return Json(new
            //{
            //    success = checkWartmark,
            //    decodedEntity = decodedEntity,
            //    msg = string.Format("水印验证：{0}",
            //            checkWartmark ? "通过" : "不通过")
            //});
        }



        [HttpPost]
        public ActionResult TemplateTest()
        {
            //string sessionId = Assiweb.GetRequestString("sid");
            //string formId = Assiweb.GetRequestString("fid");
            //string openid = Assiweb.GetRequestString("openid");
            //var sessionBag = SessionContainer.GetSession(sessionId);
            //var openId = sessionBag != null ? sessionBag.OpenId : "用户未正确登陆";

            ////KqLogic.log(sessionId + " - " + formId + " - " + openid + " - " + " - " + openId);


            //var data = new WxOpenTemplateMessage_PaySuccessNotice("在线购买", DateTime.Now, "图书众筹", "1234567890",100, "400-9939-858", "http://sdk.senparc.weixin.com");

            //TemplateDataItem td = new TemplateDataItem("小组名称");
            //TemplateDataItem td2 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"));
            //data.TemplateId = "I9kayUERwVIy3KLwmQbOfJ6t-MqS_0MO4xz-nD-7TRg";
            //data.keyword1 = td;
            //data.keyword2 = td2;

            //try
            //{
            //    Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(AppId, openid, data.TemplateId, data, formId);

            //    return Json(new Jr(1));

            //    //return Json(new { success = true, msg = "发送成功" });
            //}
            //catch (Exception ex)
            //{
            //    return Json(new Jr(false, ex.Message, ex.Message));
            //    //return Json(new { success = false, openId = openId, formId = formId, msg = ex.Message });
            //}


            string openid = Assiweb.GetRequestString("toopenid");
            var it = KqLogic.get_user(openid);
            string formId = KqLogic.GetTm(it.id);

            if (string.IsNullOrWhiteSpace(formId))
            {
                return Json(new Jr(22));
            }


            var data = new WxOpenTemplateMessage_PaySuccessNotice("在线购买", DateTime.Now, "图书众筹", "1234567890", 100, "400-9939-858", "http://sdk.senparc.weixin.com");

            TemplateDataItem td = new TemplateDataItem("小组名称");
            TemplateDataItem td2 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"));
            data.TemplateId = "I9kayUERwVIy3KLwmQbOfJ6t-MqS_0MO4xz-nD-7TRg";
            data.keyword1 = td;
            data.keyword2 = td2;

            try
            {
                KqLogic.log("it.formId 3=" + formId);
                Senparc.Weixin.Entities.WxJsonResult ex2 = Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(AppId, openid, data.TemplateId, data, formId);

                KqLogic.log("WxJsonResult:" + ex2.errcode);

                return Json(new Jr(1));
            }
            catch (Exception ex)
            {
                KqLogic.log("TemplateTest:" + ex.Message);
                return Json(new Jr(false, ex.Message, ex.Message));
            }

        }

        #endregion

        #region 调用DK接口

        #endregion

        public ActionResult u_t()
        {
            var yu = KqLogic.get_user(11835);
            var res = KqLogic.dkjk_user_upkb(yu, 1);
            return Content(res);
        }


        [HttpPost]
        public ActionResult user_instm()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            string fid = Assiweb.GetRequestString("fid");
            if (KqLogic.Check_formid(fid))
            {
                KqLogic.InsTm(uid, fid);
            }
            return Json(new Jr(1));
        }

        [HttpPost]
        public ActionResult SendTm()
        {
            string formId = Assiweb.GetRequestString("fid");
            string openid = Assiweb.GetRequestString("openid");

            var data = new WxOpenTemplateMessage_PaySuccessNotice("在线购买", DateTime.Now, "图书众筹", "1234567890", 100, "400-9939-858", "http://sdk.senparc.weixin.com");

            TemplateDataItem td = new TemplateDataItem("小组名称");
            TemplateDataItem td2 = new TemplateDataItem(DateTime.Now.ToString("yyyy-MM-dd"));
            data.TemplateId = "I9kayUERwVIy3KLwmQbOfJ6t-MqS_0MO4xz-nD-7TRg";
            data.keyword1 = td;
            data.keyword2 = td2;

            try
            {
                Senparc.Weixin.WxOpen.AdvancedAPIs.Template.TemplateApi.SendTemplateMessage(AppId, openid, data.TemplateId, data, formId);
                return Json(new Jr(1));
            }
            catch (Exception ex)
            {
                return Json(new Jr(false, ex.Message, ex.Message));
            }
        }

        [HttpPost]
        public ActionResult get_datetime()
        {
            return Json(new Jr(DateTime.Now));
        }


        [HttpPost]
        public ActionResult run_tb_user()
        {
            //string key = Assiweb.GetRequestString("key");
            //string encryptedData = Assiweb.GetRequestString("ed");
            //string iv = Assiweb.GetRequestString("iv");
            //int uid = Assiweb.GetRequestInt32("uid");

            ////LogHelper.Error(sessionId);
            ////LogHelper.Error(encryptedData);
            ////LogHelper.Error(iv);
            ////string s = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedDataBySessionId(sessionId, encryptedData, iv);

            //string s = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(key, encryptedData, iv);
            //var it = s.IndexOf("[{");
            //s = s.Substring(it);
            //var lenall = s.Length;
            //it = s.IndexOf("}]");
            //var it1 = lenall - it - 2;
            //s = s.Substring(0, s.Length - it1);
            ////s = s.Replace(@"\",@"");
            //s = "{stepInfoList:" + s + "}";

            //LogHelper.Error(s);
            ////
            //var t = Newtonsoft.Json.Linq.JObject.Parse(s);
            ////LogHelper.Error(t.ToString());
            ////LogHelper.Error(t["stepInfoList"].ToString());
            ////LogHelper.Error(t["stepInfoList"].Last.ToString());
            //Newtonsoft.Json.Linq.JArray ja = Newtonsoft.Json.Linq.JArray.Parse(t["stepInfoList"].ToString());

            ////int last = t["stepInfoList"].Count() - 1;
            //int last = ja.Count - 1;
            //var jg = ja[last]; //t["stepInfoList"].Last;
            //int step = Convert.ToInt32(jg["step"]);
            //DateTime date = Convert.ToDateTime(jg["timestamp"]).Date;
            //var ydd = KqLogic.up_user_runday(uid, step, date);

            ////var obj = new { timestamp = date, step = step };//返回值

            //int bjjt = KqLogic.get_sysset().yd_day_tj;
            //for (int i = 1; i <= bjjt; i++)
            //{
            //    last = ja.Count - 1 - i;
            //    jg = ja[last];
            //    step = Convert.ToInt32(jg["step"]);
            //    date = Convert.ToDateTime(jg["timestamp"]).Date;
            //    KqLogic.up_user_runday(uid, step, date);
            //}
            //数据已经同步
            return Json(new Jr());

        }

        [HttpPost]
        public ActionResult home_list()
        {
            var where = new Where<yd_setting>();
            where.And(d => d.cate == "home" && d.ishide == 0);

            var fs = Db.GetDb().From<yd_setting>()
                .Select(d => new { d.imgtxt, d.imgurl, d.naurl })
                .Where(where)
                .OrderByDescending(d => new { d.sort });
            var list = fs.ToList();
            return Json(new Jr(list));
        }

        [HttpPost]
        public ActionResult get_sysset()
        {
            var list = KqLogic.get_sysset();
            return Json(new Jr(list));
        }

        [HttpPost]
        public ActionResult edit_sysset()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            yd_user yu = KqLogic.get_user(uid);
            if (yu.isadmin != 1)
            {
                return Json(new Jr(21));
            }

            //int kb = Assiweb.GetRequestInt32("kblimit");
            //if (kb < 800)
            //{
            //    return Json(new Jr(22));
            //}

            int step_cal = Assiweb.GetRequestInt32("step_cal");
            int step_cake = Assiweb.GetRequestInt32("step_cake");

            int step1 = Assiweb.GetRequestInt32("step1");
            int step2 = Assiweb.GetRequestInt32("step2");
            int step3 = Assiweb.GetRequestInt32("step3");

            var syset = KqLogic.get_sysset();
            //syset.kblimit = kb;
            syset.step_cake = step_cake;
            syset.step_cal = step_cal;

            syset.step1 = step1;
            syset.step2 = step2;
            syset.step3 = step3;

            Db.GetDb().Update(syset);
            return Json(new Jr());

        }

        /// <summary>
        /// 判断获取小程序用户信息
        /// </summary>
        /// <returns></returns>
        /// 

        //        brand 手机品牌	1.5.0
        //model 手机型号
        //pixelRatio 设备像素比
        //screenWidth 屏幕宽度	1.1.0
        //screenHeight 屏幕高度	1.1.0
        //windowWidth 可使用窗口宽度
        //windowHeight 可使用窗口高度
        //language 微信设置的语言
        //version 微信版本号
        //system 操作系统版本
        //platform 客户端平台
        //fontSizeSetting 用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准，单位：px	1.5.0
        //SDKVersion 客户端基础库版本
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult saveSystemInfo()
        {
            int myid = Assiweb.GetRequestInt32("myid");
            yd_user item = KqLogic.get_user(myid);
            if (item != null) {
                string data = Assiweb.GetRequestString("data");
                var t = Newtonsoft.Json.Linq.JObject.Parse(data);
                item.brand = t["brand"].ToString();
                item.model = t["model"].ToString();
                item.version = t["version"].ToString();
                item.system = t["system"].ToString();
                item.platform = t["platform"].ToString();
                item.sdkversion = t["SDKVersion"].ToString();
                Db.GetDb().Update(item);
            }
            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult save_noyd()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            yd_user item = KqLogic.get_user(uid);
            if (item != null)
            {
                item.isnoyd = 1;
                Db.GetDb().Update(item);
            }
            return Json(new Jr());
        }
        
        [HttpPost]
        public ActionResult user_get_openid()
        {
            string openid = Assiweb.GetRequestString("openid");
            string nickname = Assiweb.GetRequestString("nickname");
            string imgurl = Assiweb.GetRequestString("imgurl");
            string unionId = Assiweb.GetRequestString("unionId");
            int isnew = 0;
            yd_user item = KqLogic.Get_User_openid(openid, nickname, imgurl, unionId,ref isnew);
            //KqLogic.log(JSON.ToJSON(item));
            item.istbkb = isnew;

            if (item.isgl == 1) {
                yd_user_gl yug = Db.GetDb().From<yd_user_gl>().Where(a => a.uid == item.id).ToFirst();
                item.code = yug.phone;
            }

            return Json(new Jr(item));
            //return Json(new Jr(new { user = item, xr = isnew }));
        }

        [HttpPost]
        public ActionResult user_get()
        {
            int id = Assiweb.GetRequestInt32("id");

            yd_user item = KqLogic.get_user(id);
            if (item == null) {
                return Json(new Jr(21));
            }

            Jr jrdk = new Jr();
            //读取
            if (item.isgl == 1)
            {
                var tmp = KqLogic.get_yd_user_gl(item.id);
                string unionId = Assiweb.GetRequestString("unionId");
                if (string.IsNullOrWhiteSpace(unionId))
                {
                    jrdk = KqLogic.dkjk_user_uid(tmp.city, tmp.kquid);
                }
                else {
                    jrdk = KqLogic.dkjk_user_phone(tmp.city, "", "", unionId);
                    //取出 mobile 数据
                    var jo = JObject.Parse(jrdk.data.ToString());
                    try
                    {
                        string MobilePhone = jo["MobilePhone"].ToString();

                        item.phone = MobilePhone;
                        item.city = tmp.city;
                        Db.GetDb().Update(item);

                        tmp.phone = MobilePhone;
                        Db.GetDb().Update(tmp);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("dkjk_user_phone_" + ex.ToString());
                    }
                }
            }
            return Json(new Jr(new { user = item, dkuser = jrdk.data }));
        }

        [HttpPost]
        public ActionResult user_list_step()
        {
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;

            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Code = Assiweb.GetRequestString("code");
            if (Assiweb.StrIsNoEmpty(Assiweb.GetRequestString("date")))
            {
                cp.Date = Assiweb.GetRequestDatetime("date");
            }
            
            cp.Id = Assiweb.GetRequestInt32("uid");

            var result = KqLogic.Get_List_User_kb(cp);

            return Json(result);
        }


        [HttpPost]
        public ActionResult user_list_kb()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            yd_user yu = KqLogic.get_user(uid);
            if (yu == null)
            {
                return Json(new Jr(21));
            }

            yd_user_gl yug = KqLogic.get_yd_user_gl(yu.id);
            if (yug == null)
            {
                return Json(new Jr(22));
            }
            Jr jr = KqLogic.dkjk_user_kblist(yu, yug);
            return Json(jr);
        }

        [HttpPost]
        public ActionResult user_save()
        {
            string json = Assiweb.GetRequestString("json");
            yd_user item = Db.GetJObject<yd_user>(json);
            item.Attach(Db.GetEs(item.id));
            Db.GetDb().Save(item);
            return Json(new Jr(item));
        }

        [HttpPost]
        public ActionResult get_self_set()
        {
            string name = Assiweb.GetRequestString("name");
            var item = KqLogic.get_sysset_self(name);
            if (item != null)
            {
                return Json(new Jr(item.value));
            }
            return Json(new Jr(""));
        }


        public ActionResult user_save_run2()
        {
            string key = "vptkB9a3VBfcqMdIf5GTkA==";
            string encryptedData = "fbYx/RJY19UALH86ns9H0Zr2BOJOfPmSyYPdwvGoiN8sikh4dWKmb/wAIot/peBTP1Er7I+dL/CxcjiNYASPWHFCvKK4VvKZ1YQ53HhOmYlywrPZH7wFdcEBqbJmUSD+g3d4+0n13erEE2MuXOpeq8RCH4LBjH7FB4/OnNVYRZcHqmBspHkfi2lH9XCeWuC2iy4MegjyxnF1NX/5heVmOqZrXX+gZBDP5ApY0ce6eHoG8DiTACNTfZXGwUhgogYnatDbhNqX9I2Oku8e9BNjAqX1tftyeHgcQbBVVEpCPB23wgq+etMs2/3idHoCgxIlOtHbZ+J56nneexsGd1D39ABxW9Ejeyt1cFeKxjlfl2AWX/fOCpwe8tIMiYjiGq7liCiXF12pMy8dGu+VcC3y0CwL+nnrWbQUIgtYulIYmrbxT6dwG48G+rm7o3x3P8zaLMw0A9L4ZpHVIndQ7mD1C3/3OuWm9OHHfiOhhMTxIsGtVfWSS+qu7nBvmKnkCOy8+BwpA07hht3qt7kyNOAukjTbsHWB7SNiXWoXU5LOag9kMJo0fOqgfFOLyi44pAUEMH5Le19J5O3fTCi82rFG8LdCyowP05uxCm1jxMvv9qtqOMFQxJQTSmkrRZ24TmDsVL7+PTqoMkB/iyYWAMuoRXywEGUm2ff8QHU1oPd1hiGA83hdRQ6mckkBXO1lX5K4o+xmGMqjazgzlnIYN7l1767xGKpABr1LtRhZN2jFOmq0ntMHS8Pv/mmsvzQGJyTAHpIeBw944PX2LGVOaiC9aXOm6VwAJBCwzUcbxxlXlGbd2Y+tamOiABQNVMvVNbvuMQ6ViS/wVI1LZqTrZ8OewPQvz5FAqMYPPWDqBgeCtcAlpbYwV0xf6VhlOWEVuDaXcmXHslxtxsRT6AIuKdrf9Sc/z9WsrUT9w4vnS7EAFgo7tysR4J2hwAFhwvpT/H1WT2cDFRQCwPAI1G/h9WsQtpZUIA5wvrlxvelMH9G3t+FxP8Ey2SlGlSlGIeou/GdymUPqoDgsxedyyRr4odLacwF/fiknG/ubkA1Hg2J02cwkBodYjslSWNTGAw3GmRo61qxc9pm7JOcw6B3gleiz2OXOc70UJm/0wRJIrlioSL115z9/+ukPkSfL0SsaCquAP0d1SUbATaXnsFY4tmNtee3sa+eSTvBkrHRgh0SiGQ1DL0n9zs4EyHG64H4+VG9gYsA7XdED2gsw4JbTQzZoxK4YplpCdqx4NPNG8bO0mdLavlU3CtM7WhUdIBqC0d68P/Vn7C/5iR23+i8FFCrqGoOzH4OQ4+65dPAU3pIqoCag7M3PhFgRTUdFlNspFb0sWbFa8UAjfBYuqSdr8RnPVX8WZ8YjY2yz+USNBGFp7Ljtgmp1s23pR2su4+Uf/YOZ3LwE/8d8hL4qiSSdMaXcV7dZuAmM+eET9AfBWLRkBqWu42E0NYLo8bVWxDFMSV/2fXfNL1TZMppZ6JPzV7B8+xAcZsiOHMy7L7BN1sjrdKfN/LgzuEmlwCiPS2IaXXU6TylS5TAt/gji0+jsH150txrxD8oPBxnew98RzPxpkUZ8kmdo78S1zBLR64Lxn9/tvZ9iLdlSaR6nD9j5Wj3OeZFrU1bmcr82lW8KmsFtdrNtPV4rF5M+neAeQxsSpb5e";
            string iv = "rYzruqczwgsv2nILqHyAJw==";
            

             
            int step = 0;
            DateTime date = DateTime.Now.Date;

            var ydc = new yd_data_day_gc();
            try
            {

                string s = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(key, encryptedData, iv);

                //LogHelper.Error("user_save_run_" + uid.ToString() + " key:" + key + " - " + "iv:" + iv + " - " + "encryptedData:" + encryptedData + " - " + "de:" + s);

                var it = s.IndexOf("[{");
                s = s.Substring(it);
                var lenall = s.Length;
                it = s.IndexOf("}]");
                var it1 = lenall - it - 2;
                s = s.Substring(0, s.Length - it1);
                //s = s.Replace(@"\",@"");
                s = "{stepInfoList:" + s + "}";
                //
                var t = Newtonsoft.Json.Linq.JObject.Parse(s);
                Newtonsoft.Json.Linq.JArray ja = Newtonsoft.Json.Linq.JArray.Parse(t["stepInfoList"].ToString());
                int last = ja.Count - 1;
                var jg = ja[last]; //t["stepInfoList"].Last;//获取最新的数据
                step = Convert.ToInt32(jg["step"]);

                date = KqLogic.GetTsDate(jg["timestamp"].ToString()).Date;
                 

            }
            catch (Exception ex)
            {
               
            }
             

            //数据已经同步
            return Json(new Jr(1));
        }


        [HttpPost]
        public ActionResult user_save_run_self()
        {
            int uid = 0;
            int step = 0;
            try
            {
                uid = Assiweb.GetRequestInt32("uid");
                step = Assiweb.GetRequestInt32("step");
            }
            catch 
            {
                return Json(new Jr("1"));
            }

            if (uid == 0 || step == 0) {
                return Json(new Jr("2"));
            }

            DateTime date = DateTime.Now.Date;
            var ydc = new yd_data_day_gc();
            var ydd = KqLogic.up_user_runday(uid, step, date);
            ydc.yddid = ydd.id;
            Db.GetDbLog().Insert(ydc);

            //数据已经同步
            return Json(new Jr(ydd));
        }

        [HttpPost]
        public ActionResult user_save_run()
        {
            string key = Assiweb.GetRequestString("key");
            string encryptedData = Assiweb.GetRequestString("ed");
            string iv = Assiweb.GetRequestString("iv");
            int uid = 0;
            try
            {
                 uid = Assiweb.GetRequestInt32("uid");
            }
            catch (Exception ex)
            {
                LogHelper.Error("user_save_run_4_" + ex.ToString());
                LogHelper.Error("user_save_run_4_" + key.ToString());
                LogHelper.Error("user_save_run_4_" + HttpContext.Request.Form.AllKeys.ToString());
                
                return Json(new Jr(""));
            }

    ////看看是否要多送
    //int zskb = 3;
    //if (zskb > 0)
    //{
    //    //需要多送,调用接口
    //    yd_user yu = KqLogic.get_user(uid);
    //    string res = KqLogic.dkjk_user_up_otherkb(yu, zskb);
    //    if (res == "0")
    //    {

    //    }
    //    else
    //    {

    //    }
    //}


    int step = 0;
            DateTime date = DateTime.Now.Date;
            var ctx = "0";
            var ydc = new yd_data_day_gc();
            try
            {

                string s = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeEncryptedData(key, encryptedData, iv);

                //LogHelper.Error("user_save_run_" + uid.ToString() + " key:" + key + " - " + "iv:" + iv + " - " + "encryptedData:" + encryptedData + " - " + "de:" + s);
                LogHelper.Error("user_save_run_xxxxx1_ " + s);

                var it = s.IndexOf("[{");
                s = s.Substring(it);
                var lenall = s.Length;
                it = s.IndexOf("}]");
                var it1 = lenall - it - 2;
                s = s.Substring(0, s.Length - it1);
                //s = s.Replace(@"\",@"");
                s = "{stepInfoList:" + s + "}";
                //

                LogHelper.Error("user_save_run_xxxxx2_ " + s);

                var t = Newtonsoft.Json.Linq.JObject.Parse(s);
                Newtonsoft.Json.Linq.JArray ja = Newtonsoft.Json.Linq.JArray.Parse(t["stepInfoList"].ToString());
                int last = ja.Count - 1;
                var jg = ja[last]; //t["stepInfoList"].Last;//获取最新的数据
                step = Convert.ToInt32(jg["step"]);

                date = KqLogic.GetTsDate(jg["timestamp"].ToString()).Date;

                ydc.uid = uid;
                ydc.step = step;
                ydc.udate = DateTime.Now.Date;
                ydc.tdate = DateTime.Now;
                if (ydc.step == 0)
                {
                    ydc.err = "user_save_run_" + uid.ToString() + "_err - 0 - " + "key:" + key + " - " + "iv:" + iv + " - " + "encryptedData:" + encryptedData;
                }
                //Db.GetDb().Insert(ydc);

            }
            catch (Exception ex)
            {
                //LogHelper.Error("user_save_run_" + uid.ToString() + "_err - " + ex.Message + " - " + "key:" + key + " - " + "iv:" + iv + " - " + "encryptedData:" + encryptedData);
                if (ex.Message.IndexOf("Padding") > -1) {
                    ctx = "1";
                }

                ydc.uid = uid;
                ydc.step = -1;
                ydc.udate = DateTime.Now.Date;
                ydc.tdate = DateTime.Now;
                ydc.err = "user_save_run_" + uid.ToString() + "_err - " + ex.Message  + " - " + "key:" + key + " - " + "iv:" + iv + " - " + "encryptedData:" + encryptedData;
            }

            if (step == 0 && (Db.GetDb()).Db.ConnectionString.IndexOf("kqyd") > -1)
            {
                Random ran = new Random();
                int RandKey = ran.Next(100, 999);
                step = RandKey;
            }

            try
            {
                decimal dizf = Convert.ToDecimal(1.00);
                if (step > 0)
                {
                    string s = KqLogic.get_sysset_self(KqLogic.step_add).value;
                    try
                    {
                        dizf = dizf + Convert.ToDecimal(s);
                        step = Convert.ToInt32(step * dizf);
                        ydc.step = step;
                    }
                    catch
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("user_save_run_2_" + ex.ToString());
            }
            var ydd = KqLogic.up_user_runday(uid, step, date);
            ydc.yddid = ydd.id;
            Db.GetDbLog().Insert(ydc);
            
            try
            {
                //打卡签到
                Get_Team_Qd(uid);
            }
            catch (Exception ex)
            {
                LogHelper.Error("user_save_run_3_" + ex.ToString());
            }

            if (ctx == "1") {
                //需要重新授权
                ydd.uid = -1;
            }

            //数据已经同步
            return Json(new Jr(ydd));
        }

        public ActionResult user_fs_tzcs()
        {
            string json = Assiweb.GetRequestString("json");

            //String json = KqLogic.Encode(Dos.Common.JSON.ToJSON(new { unionid = "oxdo21AWH5nz1ZEpQnAlTZxTDoV0", phone = "18607835800", city = "gl", uid = "123456", openid = "oxdo21AWH5nz1ZEpQnAlTZxTDoV0" }), "dkdk2017", "abcd2017");

            try
            {
                json = KqLogic.Decode(json, "dkdk2017", "abcd2017");

                var jo = JObject.Parse(json);
                string phone = jo["phone"].ToString();
                string city = jo["city"].ToString();
                string unionid = jo["unionid"].ToString();
                string uid = jo["uid"].ToString();
                string openid = jo["openid"].ToString();

                yd_jk_log yjl = new yd_jk_log();
                yjl.name = "user_fs_tzcs";
                yjl.oldurl = json;
                yjl.phone = phone;
                yjl.uid = 0;

                yd_user_gl yug = Db.GetDb().From<yd_user_gl>().Where(a => a.phone == phone).ToFirst();
                if (yug == null)
                {
                    string re = Dos.Common.JSON.ToJSON(new { success = false, re = -4, msg = "电话号码未在小程序注册绑定", err = "" });
                    yjl.res = re;
                    Db.GetDbLog().Insert(yjl);

                    return Content(re);
                }

                yd_user yu = Db.GetDb().From<yd_user>().Where(a => a.id == yug.uid).ToFirst();
                if (yu == null)
                {
                    string re = Dos.Common.JSON.ToJSON(new { success = false, re = -4, msg = "电话号码对应用户信息丢失", err = "" });
                    yjl.res = re;
                    Db.GetDbLog().Insert(yjl);
                    return Content(re);
                }

                yug.unionid = unionid;
                yug.kquid = Convert.ToInt32(uid);
                yug.kqopenid = openid;
                yug.city = city;

                yu.unionId = unionid;

                Db.GetDb().Update(yug);
                Db.GetDb().Update(yu);

                yjl.res = "ok";
                Db.GetDbLog().Insert(yjl);

                return Content(Dos.Common.JSON.ToJSON(new { success = true, re = 0 }));

            }
            catch (Exception ex)
            {
                KqLogic.log(ex.ToString(), "error_");
                return Content(Dos.Common.JSON.ToJSON(new { success = false, re = -5, msg = "json解析错误", err = ex.Message }));
            }
        }

        public ActionResult user_fs_xx()
        {
            //String st = KqLogic.Encode(Dos.Common.JSON.ToJSON(new { unionid = "oxdo21AWH5nz1ZEpQnAlTZxTDoV0", templateid = "nkHUqyaDOkgcPd13S8ELppSRpGDlWlUwMU1-rhqfEsU", keyword1 = "测试1", keyword2 = "测试2", keyword3 = "测试3", page = "pages/index/index?dh=1" }), "dkdk2017", "abcd2017");
            //string s = "nkHUqyaDOkgcPd13S8ELppSRpGDIWIUwMU1 - rhqfEsU";

            //string st2 = System.Web.HttpContext.Current.Server.UrlEncode(st);

            //return Content(st2);
            //string st = System.Web.HttpContext.Current.Server.UrlEncode(@"xD24U1WX2IKRAj2bz1dgZvMMcTe4DGloeBQOG06bMnkzC+1GnVV4h78afwlfEZw+mdh1LdaFPa+pe7VJfs9DFlTFvvB892Q84a5AEtRrut5qntssHXQVctBToSeIirz3kklqevNP0RpnWk7Eg9xe4CcKyiTdPsOcSwTr3GjBhgaQjD10aAZCDPxbk1tZmMiQNOzinFLkdRg/ZsNk2CS20nBOQ+AJH7FkdLkfS+UgspIW8Zr4bslhs3xcF8kfwHOGg56Wfp9sqf8=");

            //string st2 = System.Web.HttpContext.Current.Server.UrlDecode("B4N1fWsyt5e%2bC9zbDkOgdqkW3zNgsTcCPSHVUP5yO4C5xE6oa7JQYr%2fxSOg3wW74Fge%2fB%2fZz0Wwl26N0AZPK5IzDAXgafs4IQEjUKSCEc7DGRuc8ETUbboSq23lGOGXtLnkzyXm0SuV%2fTV%2fcfHsTUIldK5c%2f9P2amfrdq5qHVMJc%2fTDx4Q2FEkwnzmLqa5D3");

            //string stt = KqLogic.Decode(st2, "dkdk2017", "abcd2017");

            //string st2 = System.Web.HttpContext.Current.Server.UrlDecode(st);

            string json = Assiweb.GetRequestString("json");
            try
            {
               

                json = KqLogic.Decode(json, "dkdk2017", "abcd2017");
                KqLogic.log("2 _ " + json, "error_");
                var jo = JObject.Parse(json);
                string unionid = jo["unionid"].ToString();//"oxdo21PTieOvgSMyTNjq3xx9iF2c";//
                string page = jo["page"].ToString();

                yd_jk_log yjl = new yd_jk_log();
                yjl.name = "user_fs_xx";
                yjl.oldurl = json;
                yjl.phone = unionid;
                yjl.uid = 0;
                yjl.credate = DateTime.Now;

                string msg = "";

                yd_user yu = Db.GetDb().From<yd_user>().Where(a => a.unionId == unionid).ToFirst();
                if (yu == null)
                {
                    string re2 = Dos.Common.JSON.ToJSON(new { success = false, re = -3, msg = "unionid异常,用户丢失", err = "" });
                    yjl.res = re2;
                    Db.GetDbLog().Insert(yjl);

                    return Content(Dos.Common.JSON.ToJSON(new { success = false, re = -3, msg = "unionid异常,用户丢失" }));
                }

                //yd_user_gl yug = Db.GetDb().From<yd_user_gl>().Where(a => a.uid == yu.id).ToFirst();
                //if (yug == null || string.IsNullOrWhiteSpace(yug.kqopenid))
                //{
                //    return Content(Dos.Common.JSON.ToJSON(new { success = false, re = -4, msg = "yug异常" }));
                //}
                //int uid = yug.uid;
                int uid = yu.id;
                //new TemplateDataItem("每一步，都算数！步数换成的K币，可以兑换面包、蛋糕、冰淇淋、优惠码哦！点击进入兑换页面");//获取积分

                var data = new WxOpenTemplateMessage_PaySuccessNotice("", DateTime.Now, "", "", 100, "", "");
                data.TemplateId = jo["templateid"].ToString().Trim(); //"nkHUqyaDOkgcPd13S8ELppSRpGDlWlUwMU1-rhqfEsU";

                string k1 = Jotstr(jo, "keyword1");
                string k2 = Jotstr(jo, "keyword2");
                string k3 = Jotstr(jo, "keyword3");
                string k4 = Jotstr(jo, "keyword4");
                string k5 = Jotstr(jo, "keyword5");
                string k6 = Jotstr(jo, "keyword6");

                k1 = "123";
                k2 = "abc";
                page = "/page/index";

                if (!string.IsNullOrWhiteSpace(k1))
                {
                    data.keyword1 = new TemplateDataItem(k1);//昵称
                }

                if (!string.IsNullOrWhiteSpace(k2))
                {
                    data.keyword2 = new TemplateDataItem(k2);//昵称
                }

                if (!string.IsNullOrWhiteSpace(k3))
                {
                    data.keyword3 = new TemplateDataItem(k3);//昵称
                }

                if (!string.IsNullOrWhiteSpace(k4))
                {
                    data.keyword4 = new TemplateDataItem(k4);//昵称
                }

                if (!string.IsNullOrWhiteSpace(k5))
                {
                    data.keyword5 = new TemplateDataItem(k5);//昵称
                }

                if (!string.IsNullOrWhiteSpace(k6))
                {
                    data.keyword6 = new TemplateDataItem(k6);//昵称
                }


                int re = KqLogic.SendTm_common_team_tz_dh(yu, data, page, ref msg);
                if (re == 0)
                {
                    string re2 = Dos.Common.JSON.ToJSON(new { success = false, re = 0, msg = "ok", err = "ok" });
                    yjl.res = re2;
                    Db.GetDbLog().Insert(yjl);

                    return Content(Dos.Common.JSON.ToJSON(new { success = true, re = 0, msg = "ok" }));
                }
                else
                {
                    string re2 = Dos.Common.JSON.ToJSON(new { success = false, re = -1, msg = "发送消息失败", err = msg });
                    yjl.res = re2;
                    Db.GetDbLog().Insert(yjl);

                    return Content(Dos.Common.JSON.ToJSON(new { success = false, re = re, msg = msg }));
                }
            }
            catch (Exception ex)
            {
                KqLogic.log(ex.ToString() + " _ " + json, "error_");
                return Content(Dos.Common.JSON.ToJSON(new { success = false, re = -5, msg = "方法异常_" + ex.ToString() }));
            }
        }

        public ActionResult user_fs_userinfo()
        {
            string json = Assiweb.GetRequestString("json");
            json = KqLogic.Decode(json, "dkdk2017", "abcd2017");
            var jo = JObject.Parse(json);

            string phone = jo["phone"].ToString(); //Assiweb.GetRequestString("phone");
            string code = jo["code"].ToString(); //Assiweb.GetRequestString("code");
            string city = jo["city"].ToString(); //Assiweb.GetRequestString("phone");
            int pageindex = Convert.ToInt32(jo["pageindex"].ToString()); //Assiweb.GetRequestInt32("pageindex");
            int pagesize = Convert.ToInt32(jo["pagesize"].ToString()); //Assiweb.GetRequestInt32("pagesize");

            //string phone =Assiweb.GetRequestString("phone");
            //string code = Assiweb.GetRequestString("code");
            //int pageindex = Assiweb.GetRequestInt32("pageindex");
            //int pagesize = Assiweb.GetRequestInt32("pagesize");

            string sql = "  from yd_user a left join yd_user_gl b on a.id = b.uid  where 1=1 ";
            if (!string.IsNullOrWhiteSpace(phone)) {
                sql += " and b.phone like '%" + phone + "%'";
            }

            if (!string.IsNullOrWhiteSpace(code))
            {
                sql += " and a.code = '" + code + "'";
            }

            if (!string.IsNullOrWhiteSpace(city))
            {
                sql += " and b.city = '" + city + "'";
            }

            string countsql = "select count(*) " + sql;
            //System.Data.Common.DbCommand dc = new System.Data.Common.DbCommand();

            int total = Convert.ToInt32(MysqlHelper.ExecuteFirst(countsql, null));

            string dtsql = " select a.nickname,a.imgurl,a.isgl,a.unionid,a.code,b.phone,b.city " + sql + " ORDER BY a.id asc  limit " + pageindex * pagesize + " , " +  pagesize;
            DataTable dt = MysqlHelper.ExecuteDataTable(dtsql, null);

            return Content(Dos.Common.JSON.ToJSON(new { success=true, total = total, rows = dt }));
        }

        public string Jotstr(JObject jo, string name)
        {
            try
            {
                return jo[name].ToString();
            }
            catch (Exception ex)
            {
                KqLogic.log(ex.ToString(), "error");
                return null;
            }
        }

        [HttpPost]
        public ActionResult user_save_kb()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            int step = Assiweb.GetRequestInt32("step");

            string fid = Assiweb.GetRequestString("fid");
            if (KqLogic.Check_formid(fid))
            {
                KqLogic.InsTm(uid, fid);
            }

            DateTime date;
            string sdate = Assiweb.GetRequestString("date");
            if (string.IsNullOrWhiteSpace(sdate))
            {
                KqLogic.log("user_save_kb - dt2 - para:" + sdate);
                date = DateTime.Now;
            }
            else
            {
                try
                {
                    DateTime dt = Assiweb.GetRequestDatetime("date");
                    date = dt.Date;
                }
                catch (Exception ex)
                {

                    KqLogic.log("user_save_kb - dt -:" + ex.ToString() + " - para:" + sdate);
                    //这里处理的是提交上来的日期
                    return Json(new Jr(55));
                }
            }



            //用户获取kb
            var kys = KqLogic.get_sysset();
            yd_data_day ydd = KqLogic.up_user_runday(uid, step, date);
            DateTime dtnow = DateTime.Now;
            //int kbsj = Assiweb.GetInt32(WebConfigurationManager.AppSettings["kbsj"].ToString());
            //if (kbsj > 0) {
            //    DateTime dtc = ydd.kbdate.Date.AddHours(kbsj);
            //    if (dtnow > dtc)
            //    {
            //        return Json(new Jr(36));
            //    }
            //}

            int getkb = 0;
            int kblimit = 0;

            if (kys.step1 > 0)
            {
                kblimit++;
            }

            if (kys.step2 > 0)
            {
                kblimit++;
            }

            if (kys.step3 > 0)
            {
                kblimit++;
            }

            if (ydd.kb >= kblimit)
            {
                return Json(new Jr(31));
            }


            if (kys.step1 > 0)
            {
                kblimit = kys.step1;
                if (step < kblimit)
                {
                    return Json(new Jr(new { re = 21, kblimit = kblimit }));
                }
                else
                {

                    //判断是否已经获取了kb
                    if (ydd.step1 == 0)
                    {
                        ydd.step1 = step;
                        ydd.date1 = dtnow;
                        getkb++;
                    }
                }
            }

            if (kys.step2 > 0)
            {
                kblimit = kys.step2;
                if (step < kblimit)
                {
                    if (getkb == 0)
                    {
                        return Json(new Jr(new { re = 21, kblimit = kblimit }));
                    }
                }
                else
                {
                    //判断是否已经获取了kb
                    if (ydd.step2 == 0)
                    {
                        ydd.step2 = step;
                        ydd.date2 = dtnow;
                        getkb++;
                    }
                }
            }

            if (kys.step3 > 0)
            {
                kblimit = kys.step3;
                if (step < kblimit)
                {
                    if (getkb == 0)
                    {
                        return Json(new Jr(new { re = 21, kblimit = kblimit }));
                    }
                }
                else
                {
                    //判断是否已经获取了kb
                    if (ydd.step3 == 0)
                    {
                        ydd.step3 = step;
                        ydd.date3 = dtnow;
                        getkb++;
                    }
                }
            }


            //生成领取记录? 还是直接用 data_day 表
            if (getkb > 0)
            {
                //用户增加kb
                var yu = KqLogic.get_user(uid);

                //推送新增kb接口
                string res = "1";
                if (!Assiweb.GetIsLocal())
                {
                    res = KqLogic.dkjk_user_upkb(yu, getkb);
                }
                

                if (res == "0")
                {
                    KqLogic.log("err: dkjk_user_upkb _ " + ydd.id);
                    //这里应该发送微信消息通知,或者发送邮件
                    //return Json(new Jr(22));
                    return Json(new Jr(23));
                }
                else if (res == "1")
                {
                    //更新当天的数据kb
                    ydd.kb = ydd.kb + getkb;
                    ydd.kbsum = ydd.kbsum + 1;
                    ydd.kbdate = dtnow;
                    Db.GetDb().Update(ydd);

                    yu.ydkb = yu.ydkb + getkb;
                    Db.GetDb().Update(yu);
                }
                else
                {
                    return Json(new Jr(22));
                }

                //如果用户已经同步了账号的 就同步,不同步账号的就免了.
                //现在改为要求必须同步才能获取k币
                //if (yu.isgl == 1)
                //{
                //    KqLogic.dkjk_user_upkb(yu, KqLogic.day_kb);
                //}
                //else {
                //    //调用接口 通知
                //    KqLogic.dkjk_user_upkb(yu, KqLogic.day_kb);
                //}

            }
            else
            {
                return Json(new Jr(22));
            }

            //成功获取kb 这个时候判断 是连续几天获取了
            int[] kbdays = KqLogic.Get_Kb_Days(uid);

            return Json(new Jr(new { ydd = ydd, kb = getkb, kbdays = kbdays[0], zskb = kbdays[1] }));
        }

        /// <summary>
        /// 注册手机号 + 同步手机号
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult user_save_zc()
        {
            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");
            if (city == "lz" || city == "nn" || city == "qt" || city == "gl")
            {

            }
            else {
                return Json(new Jr(28));
            }

            int uid = Assiweb.GetRequestInt32("uid");
            string openid = Assiweb.GetRequestString("openid");
            string unionId = Assiweb.GetRequestString("unionId");

            string cate = Assiweb.GetRequestString("cate");

            string yzm = Assiweb.GetRequestString("yzm");

            string xm = Assiweb.GetRequestString("xm");
            string dlm = Assiweb.GetRequestString("dlm");
            string mm = Assiweb.GetRequestString("mm");

            //判断验证码是否通过 验证码 要跟 小程序的openid 一起才有效
            //yd_yzm yy = Db.GetDb().From<yd_yzm>().Where(a => a.yzm == yzm && a.phone == phone && a.openid == openid).OrderByDescending(a => a.id).ToFirst();
            //if (Assiweb.IsNull(yy)) {
            //    return Json(new Jr(21));
            //}

            //if (yy.qxdate < DateTime.Now) {
            //    return Json(new Jr(22));
            //}

            //Jr jr = KqLogic.dkjk_yzm_check(yzm, phone);
            //if (!jr.success)
            //{
            //    return Json(new Jr(22));
            //}



            var yu = KqLogic.get_user(uid);
            if (yu.isgl == 1)
            {
                KqLogic.log("user_save_zc_24_" + uid.ToString());
                return Json(new Jr(24));
            }

            Jr jr = new Jr();
            KqLogic.log(cate + "_" + openid + "_1");
            //if (cate == "zc")
            //{
            //    jr = KqLogic.dkjk_user_zc(city, phone,xm,dlm,mm);
            //}
            //else
            //{
            //同步获取用户信息
            jr = KqLogic.dkjk_user_phone(city, phone, openid, unionId);
            //}

            //return Json(new Jr(24));

            string kqopenid = "";
            int kquid = 0;
            int kbnow = 0;
            int kbxf = 0;


            var jo = JObject.Parse(jr.data.ToString());
            bool bl = (bool)jo["success"];
           
            //返回用的  jr 读取出这些内容
            if (!bl)
            {
                //新增
                jr = KqLogic.dkjk_user_zc(city, phone, phone, phone, phone, yzm, openid, unionId);

                jo = JObject.Parse(jr.data.ToString());
                bl = (bool)jo["success"];
                yu.isnew = 1;
                if (!bl)
                {
                    string msg = jo["msg"].ToString();
                    if (msg.IndexOf("验证码") > -1) {
                        return Json(new Jr(31));
                    }
                    if (msg.IndexOf("被注册") > -1)
                    {
                        return Json(new Jr(32));
                    }
                    KqLogic.log("msg_" + msg);
                    return Json(new Jr(25));


                }

                kqopenid = jo["openid"].ToString();
                kquid = Convert.ToInt32(jo["uid"].ToString());
                kbnow = Convert.ToInt32(jo["kbnow"].ToString());
                kbxf = Convert.ToInt32(jo["kball"].ToString());
            }
            else {
                bool bl2 = KqLogic.dkjk_yzm_check(yzm, phone, openid, "");
                if (!bl2)
                {
                    return Json(new Jr(31));
                }
                //这个时候要判断用户是否是注册用户 删除第几名后 再次登录的情况




                yu.isnew = 0;

                kqopenid = jo["openid"].ToString();
                kquid = Convert.ToInt32(jo["uid"].ToString());
                kbnow = Convert.ToInt32(jo["kbnow"].ToString());
                kbxf = Convert.ToInt32(jo["kball"].ToString());

            }

             

            KqLogic.log(cate + "_" + openid + "_2");

            var yug = Db.GetDb().From<yd_user_gl>().Where(a => a.kquid == kquid && a.city == city).ToFirst();
            if (!Assiweb.IsNull(yug))
            {
                KqLogic.log("user_save_zc_26_" + kquid.ToString() + "_" + city);
                return Json(new Jr(26));
            }
            
            yu.isgl = 1;
            yu.istbkb = 1;//现在是不同步账号 不能领取K币
            yu.phone = phone;

            yug = new yd_user_gl();
            yug.city = city;
            yug.kqopenid = kqopenid;
            yug.kquid = kquid;
            yug.openid = openid;
            yug.phone = phone;
            yug.uid = uid;
            yug.unionid = "";
            Db.GetDb().Insert(yug);

            ////注册成功 即刻同步kb
            //if (yu.istbkb == 0)
            //{
            //    KqLogic.log(cate + "_" + openid + "_3");
            //    int kb = yu.ydkb;
            //    jr = KqLogic.dkjk_user_upkb(yu, kb);

            //    if (jr.success)
            //    {
            //        yu.istbkb = 1;
            //    }
            //    else {
            //        //做个日志记录,好去做同步信息
            //        //这里要推送模板信息告诉用户 同步失败
            //    }
            //}

            Db.GetDb().Update(yu);
            KqLogic.log(cate + "_" + openid + "_4");

            return Json(new Jr(new { kbnow = kbnow, kbxf = kbxf, isnew = yu.isnew }));
        }

        public ActionResult usersavedknew()
        {
            string openid = Assiweb.GetRequestString("openid");
            int uid = Assiweb.GetRequestInt32("uid");

            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");
            string openid2 = Assiweb.GetRequestString("openid2");//公众号的openid
            string unionId = Assiweb.GetRequestString("unionid2");

            //判断是否已经是注册的. 如果是就是切换城市而已;

            

            var yu = KqLogic.get_user(uid);
            if (yu.isgl == 1)
            {
                KqLogic.log("user_save_zc_241_" + openid.ToString());
                return Json(new Jr(24));

            }

            Jr jr = new Jr();
            //同步获取用户信息
            jr = KqLogic.dkjk_user_phone(city, phone, openid, unionId); 
 

            string kqopenid = "";
            int kquid = 0;
            int kbnow = 0;
            int kbxf = 0;


            var jo = JObject.Parse(jr.data.ToString());
            bool bl = (bool)jo["success"];

            //返回用的  jr 读取出这些内容
            if (!bl)
            {
                KqLogic.log("user_save_zc_242_" + openid.ToString());
                return Json(new Jr(24));
            }
            else
            {
                yu.isnew = 1;
                kqopenid = jo["openid"].ToString();
                kquid = Convert.ToInt32(jo["uid"].ToString());
                kbnow = Convert.ToInt32(jo["kbnow"].ToString());
                kbxf = Convert.ToInt32(jo["kball"].ToString());

            }

           
            var yug = Db.GetDb().From<yd_user_gl>().Where(a => a.kquid == kquid && a.city == city).ToFirst();
            if (!Assiweb.IsNull(yug))
            {
                KqLogic.log("user_save_zc_26_" + kquid.ToString() + "_" + city);
                return Json(new Jr(26));
            }

            yu.isgl = 1;
            yu.istbkb = 1;//现在是不同步账号 不能领取K币
            yu.phone = phone;

            yug = new yd_user_gl();
            yug.city = city;
            yug.kqopenid = kqopenid;
            yug.kquid = kquid;
            yug.openid = openid;
            yug.phone = phone;
            yug.uid = uid;
            yug.unionid = "";
            Db.GetDb().Insert(yug);


            Db.GetDb().Update(yu);

            return Json(new Jr(new { kbnow = kbnow, kbxf = kbxf, isnew = yu.isnew }));
        }


        [HttpPost]
        public ActionResult user_get_phone_isgl()
        {
            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");

            //判断手机号是否已经同步过了
            yd_user_gl ydg = Db.GetDb().From<yd_user_gl>().Where(a => a.phone == phone).ToFirst();
            if (!Assiweb.IsNull(ydg))
            {
                return Json(new Jr(22));
                //做个
            }

            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult user_get_yzm()
        {
            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");
            int uid = Assiweb.GetRequestInt32("uid");
            string openid = Assiweb.GetRequestString("openid");

            //判断手机号是否已经同步过了
            //yd_user_gl ydg = Db.GetDb().From<yd_user_gl>().Where(a => a.phone == phone).ToFirst();
            //if (!Assiweb.IsNull(ydg))
            //{
            //    return Json(new Jr(22));
            //}


            bool bl = KqLogic.dkjk_yzm("test",phone,openid,"");
            if (!bl)
            {
                return Json(new Jr(21));
            }

            //验证码跟期限 这里最好跟openid 结合起来,避免别的机器在用 //存到数据库去
            //DateTime date = DateTime.Now.AddMinutes(30);
            //string yzm = jr.data.ToString();

            //yd_yzm yy = new yd_yzm();
            //yy.openid = openid;
            //yy.qxdate = date;
            //yy.yzm = yzm;
            //yy.uid = uid;
            //yy.phone = phone;
            //yy.city = city;
            //Db.GetDb().Insert(yy);
            //new Jr(yy)
            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult user_check_yzm()
        {
            //return Json(new Jr());

            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");
            string yzm = Assiweb.GetRequestString("yzm");
            string openid = Assiweb.GetRequestString("openid");


            //bool bl = KqLogic.dkjk_yzm_check(yzm, phone, openid, "");
            //if (!bl)
            //{
            //    return Json(new Jr(21));
            //}
            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult user_get_dkuser_phone()
        {
            string phone = Assiweb.GetRequestString("phone");
            string city = Assiweb.GetRequestString("city");
            string openid = Assiweb.GetRequestString("openid");
            string unionId = Assiweb.GetRequestString("unionId");

            //判断手机号是否已经同步过了
            yd_user_gl ydg = Db.GetDb().From<yd_user_gl>().Where(a => a.phone == phone).ToFirst();
            if (!Assiweb.IsNull(ydg))
            {
                return Json(new Jr(22));
            }

            Jr jr = KqLogic.dkjk_user_phone(city, phone, openid, unionId);
            if (jr.success == true)
            {
                //通过说明手机号已经注册,用同步方式即可
                return Json(new Jr(21));
            }
            else
            {
                //说明可以注册
                return Json(new Jr(jr.data));
            }
        }

        [HttpPost]
        public ActionResult user_get_dkuser_uid()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            string city = Assiweb.GetRequestString("city");

            KqLogic.dkjk_user_uid(city, uid);

            //验证码跟期限
            return Json(new Jr(new { kqopenid = "", uid = "", kb = 0 }));
        }

        [HttpPost]
        public ActionResult hb_home()
        {
            //string img1 = Server.MapPath(@"image/4330.png");
            //string img2 = Server.MapPath(@"image/123.jpg");
            //string img3 = Server.MapPath(@"image/52.png");
            //getMixImage(img1, img2, 20, 200, 100, 100, img3, 200, 100, 100, 100, "你大xafads爷???", 100, 500);
            int tid = Assiweb.GetRequestInt32("tid");
            int uid = Assiweb.GetRequestInt32("uid");
            int zjbs = Assiweb.GetRequestInt32("zjbs");

            

            var item = KqLogic.get_user(uid);
            var ydd = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == DateTime.Now.Date).ToFirst();
            if (item == null || ydd == null) {
                KqLogic.log("hb_home _ uid" + uid.ToString());
                return Json(new Jr(""));
            }

            if (uid == 44) {
                uid = 1;
            }
            string name = item.nickname;
            string img = item.imgurl;
            string path = @"/image/hb/" + System.Guid.NewGuid().ToString() + ".jpg";

            string background = Server.MapPath(@"/image/background/bg_" + tid.ToString() + ".jpg");
            bool bl = System.IO.File.Exists(background);
            if (bl == false) {
                int bgnext = Assiweb.GetInt32(WebConfigurationManager.AppSettings["bgnext"].ToString());
                bgnext = bgnext + 1;
                Random rd = new Random();
                int t = rd.Next(1, bgnext);
                background = Server.MapPath(@"/image/background/bg_" + t.ToString() + ".jpg");
            }

            string code = "";// Server.MapPath(@"/image/code/qrcode.jpg");
            string scene = "u_f-" + uid.ToString();

            string avar = Server.MapPath(@"/image/avar/" + uid.ToString() + ".jpg");
            KqLogic.DownPic(img, avar);

            string kouhao = "每一步，都算数";
            string bushu = ydd.step.ToString();

            int qrw = 0;
            int qrh = 0;
            int qrwh = 0;

            int avw = 0;
            int avh = 0;
            int avwh = 0;

            int w = 430;
            if (tid > 0) {
                var team = Db.GetDb().From<yd_team>().Where(a => a.id == tid).First();
                //判断team是不是 10000 步群  是的话 要变换指定签到数量的背景
                if (item != null)
                {
                    scene = "";
                    code = Server.MapPath(@"/image/code/qrcode_team_" + tid.ToString() + ".png");
                    if (!System.IO.File.Exists(code))
                    {
                        scene += ",ti-" + tid.ToString();
                        WxAppApi.GetWxaCode_unlimit(AppId, code, "pages/index/index", scene, 430, tid);
                    }

                    if (team.jstype == KqLogic.jstype_10000)
                    {
                        int qdc = 0;
                        var qd = Db.GetDb().From<yd_data_qd>().Where(a => a.tid == tid && a.uid == uid && a.credate == DateTime.Now.Date).ToFirst();
                        if (qd != null)
                        {
                            //表示用户当天已经签到 并且得到连续签到天数
                            qdc = Convert.ToInt32(qd.dqqd);
                            //生成了分享的key但是不增加步数了 但是同样记录分享者是谁
                            scene += ",ti-" + tid.ToString() + ",u_f-" + uid.ToString() + "-" + tid.ToString();
                        }
                        else
                        {
                            //没有表示步数不够 需要大家的支持贡献
                            //生成了能够增加步数的key
                            if (zjbs == 1)
                            {
                                qdc = 10000;
                                scene += ",ti-" + tid.ToString() + ",uft-" + uid.ToString() + "-" + tid.ToString();

                            }
                            else {
                                scene += ",ti-" + tid.ToString() + ",zjbs-1";
                            }
                        }

                        //scene = "u_f-1699,team_in-291,u_f_t-1699-291";

                        //取得了 不同的背景图了
                        background = Server.MapPath(@"/image/background/qd/" + qdc.ToString() + ".jpg");

                        w = 430;
                        code = Server.MapPath(@"/image/code/qd/qrcode_team_" + tid.ToString() + "_uid_" + uid.ToString() + "_" + w.ToString() + ".png");

                        string sflod = Server.MapPath(@"/image/code/qd");
                        if (!System.IO.Directory.Exists(sflod))
                        {
                            System.IO.Directory.CreateDirectory(sflod);
                        }

                        if (System.IO.File.Exists(code))
                        {
                            System.IO.File.Delete(code);
                        }

                        WxAppApi.GetWxaCode_unlimit(AppId, code, "pages/index/index", scene, w, tid);

                        //这需要一个新的图片生成方法
                        qrw = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrw_10000"].ToString());
                        qrh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrh_10000"].ToString());
                        qrwh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrwh_10000"].ToString());

                        avw = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avw_10000"].ToString());
                        avh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avh_10000"].ToString());
                        avwh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avwh_10000"].ToString());

                        int zl = 0;
                        if (qdc == 10000)
                        {
                            string s = KqLogic.get_sysset_self(KqLogic.fx_step_add).value;
                            zl = Assiweb.GetInt32(s);
                        }

                        KqLogic.getMixImage_3(Server.MapPath(path), background, name, bushu, code, qrw, qrh, qrwh, avar, avw, avh, avwh, zl, qdc);

                        //WxAppApi.GetWxaCode_unlimit(AppId, Server.MapPath(@"image/123123.png"), "pages/index/index");
                        return Json(new Jr(path));

                    }
                }
            }
            else
            {
                //生成一个带自己分享id的二维码的图片,这个二维码不用每次都生成
                code = Server.MapPath(@"/image/code/qrcode_user_" + uid.ToString() + ".png");
                if (!System.IO.File.Exists(code))
                {
                    WxAppApi.GetWxaCode_unlimit(AppId, code, "pages/index/index", scene, 430, tid);
                }
            }
            
            string dpm = KqLogic.GetDayPm(uid).ToString();
            //计算cal 蛋糕 kb
            int step = ydd.step;
            decimal cal = 0;
            decimal ck = 0;
            int kb = 0;
            var ys = KqLogic.get_sysset();
            if (ys != null)
            {
                decimal calb = Convert.ToDecimal(ys.step_cal);
                decimal ckb = Convert.ToDecimal(ys.step_cake);

                decimal step2 = Convert.ToDecimal(step);

                if (calb != 0)
                {
                    cal = Assiweb.MyDecimalRound(Convert.ToDecimal(step2 / calb), 1);
                }

                if (ckb != 0)
                {
                    ck = Assiweb.MyDecimalRound(Convert.ToDecimal(step2 / ckb), 1);
                }

                if (step > ys.step1)
                {
                    kb++;
                }
                if (step > ys.step2)
                {
                    kb++;
                }
                if (step > ys.step3)
                {
                    kb++;
                }
            }

            string[] astr = { cal.ToString(), ck.ToString(), kb.ToString() };

             qrw = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrw"].ToString());
             qrh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrh"].ToString());
             qrwh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["qrwh"].ToString());

             avw = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avw"].ToString());
             avh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avh"].ToString());
             avwh = Assiweb.GetInt32(WebConfigurationManager.AppSettings["avwh"].ToString());

            KqLogic.getMixImage_2(Server.MapPath(path), background, name, bushu, dpm, astr, code,qrw,qrh,qrwh,avar,avw,avh,avwh);

            //WxAppApi.GetWxaCode_unlimit(AppId, Server.MapPath(@"image/123123.png"), "pages/index/index");
            return Json(new Jr(path));
        }

        [HttpPost]
        public ActionResult team_get()
        {
          
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            string code = Assiweb.GetRequestString("code");
            yd_team item = Db.GetDb().From<yd_team>().Where(d => d.id == id).ToFirst();
            if (code == "all")
            {
                return Json(new Jr(item));
            }
            else
            {
                var where = new Where<yd_data>();
                where.And(a => a.tid == id);

                var fs = Db.GetDb().From<yd_data>().Where(where);
                //获取总步数 总人数 
                int nrs = fs.Count();
                //总步数

                WhereClip wc = new WhereClip(" tid =  " + id.ToString());
                int nbs = Db.GetDb().Sum<yd_data, int>(yd_data._.step, wc);

                int pmtd = 0;
                int pmzd = 0;


                //result.data , pm = null
                //获取当天 组的排名  团队的排名

                //竞速比赛 要读取配置数据 用个json文件来记录吧

                //计算记录
                int dist = 0;
                yd_data_js ydj = null;
                if (item.type == 1 || item.type == 2)
                {
                    dist = Convert.ToInt32(item.diff);
                   
                }

                if (item.type == 1) {
                    ydj = Db.GetDb().From<yd_data_js>().Where(d => d.tid == item.id && d.uid == uid).ToFirst();
                }

                if (item.type == 2)
                {
                    ydj = Db.GetDb().From<yd_data_js>().Where(d => d.tid == item.id && d.uid == uid && d.credate == DateTime.Now.Date).ToFirst();

                    if (ydj == null) {
                        ydj = new yd_data_js();
                        ydj.uid = uid;
                        ydj.tid = item.id;
                        ydj.startdate = DateTime.Now;
                        ydj.enddate = DateTime.Now;
                        ydj.startdura = 0;
                        ydj.isstart = 0;
                        ydj.speed = 0;
                        ydj.second = 0;
                        ydj.enddura = 0;
                        ydj.isend = 0;
                        ydj.credate = DateTime.Now.Date;
                        Db.GetDb().Insert(ydj);
                    }
                }

                //long tgb = item.bdate.Ticks;
                //int tgn = DateTime.Now.Millisecond;
                //int tge = item.edate.Millisecond;

                string jstxt = "";
                if (item.jstype == KqLogic.jstype_10000) {
                    var data = KqLogic.get_10000_wp(uid, id,ref jstxt);
                }

                DateTime tgb = item.bdate;
                DateTime tgn = DateTime.Now;
                DateTime tge = item.edate;

                var isend = 0;
                var isstart = 0;

                if (item.type == 2) {
                    //看看用户是否有启动记录
                    if (ydj != null)
                    {
                        isend = ydj.isend;
                        isstart = ydj.isstart;

                        if (isend == 1)
                        {
                            //系统结束
                        }
                        else
                        {
                            if (isstart == 0)
                            {
                                tgb = DateTime.Now;
                                tge = DateTime.Now.AddHours(Convert.ToDouble(item.limithour));
                            }
                            else {
                                tgb = ydj.startdate;
                                tge = ydj.startdate.AddHours(Convert.ToDouble(item.limithour));
                            }
                        }
                    }
                    else {
                        tgb = DateTime.Now;
                        tge = DateTime.Now.AddHours(Convert.ToDouble(item.limithour));
                    }
                }

                return Json(new Jr(new { team = item, tgb = tgb, tgn = tgn, tge = tge, userall = nrs, stepall = nbs, pmtd = pmtd, pmzd = pmzd, jspz = new { mapscale = 14, wh = 35, distance = "起点至终点直线距离 " + dist.ToString() + " 米" }, ydj = ydj, jstxt = jstxt, isstart = isstart, isend = isend, pm = 0 }));
            }
        }

        [HttpPost]
        public ActionResult team_data_get()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            yd_data yd = Db.GetDb().From<yd_data>().Where(a => a.tid == id && a.uid == uid).ToFirst();
            return Json(new Jr(yd));
        }

        [HttpPost]
        public ActionResult team_list()
        {
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;

            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Name = Assiweb.GetRequestString("name");
            cp.Code = Assiweb.GetRequestString("code");
            cp.Mobile = Assiweb.GetRequestString("mobile");
            KqLogic.log(cp.Mobile);
            var result = KqLogic.Get_List_Team(cp);

            return Json(result);
        }

        [HttpPost]
        public ActionResult team_list_all()
        {
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;

            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            var result = KqLogic.Get_List_Team_all(cp);

            return Json(result);
        }

        [HttpPost]
        public ActionResult team_user_out()
        {
            //用户id
            int id = Assiweb.GetRequestInt32("id");
            int ot = Assiweb.GetRequestInt32("ot");
            int tid = Assiweb.GetRequestInt32("tid");

            var yd = Db.GetDb().From<yd_data>().Where(a => a.uid == id && a.tid == tid).ToFirst();
            Db.GetDb().Delete(yd);

            var t = Db.GetDb().From<yd_team>().Where(a => a.id == tid).ToFirst();
            if (t.type == 1)
            {
                var djs = Db.GetDb().From<yd_data_js>().Where(a => a.uid == id && a.tid == tid).ToFirst();
                Db.GetDb().Delete(djs);
            }

            if (t.type == 2)
            {
                List<yd_data_js> ldjs = Db.GetDb().From<yd_data_js>().Where(a => a.uid == id && a.tid == tid).ToList();
                Db.GetDb().Delete<yd_data_js>(ldjs);
            }

            //修改 数据, 清空数据
            //var yd = Db.GetDb().From<yd_data>().Where(a => a.id == id).ToFirst();
            if (ot == 1)
            {
                var it = new yd_team_out();
                it.uid = id;
                it.tid = tid;
                Db.GetDb().Insert(it);
            }

            int cl = Db.GetDb().From<yd_group>().Where(d => d.tid == yd.tid).Count();
            if (cl == 0)
            {
                var yt = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
                if (!Assiweb.IsNull(yt))
                {
                    yt.usernum = yt.usernum - 1;
                    Db.GetDb().Update(yt);
                }
            }
            else
            {
                if (yd.gid > 0)
                {
                    var yg = Db.GetDb().From<yd_group>().Where(a => a.id == yd.gid).ToFirst();
                    if (!Assiweb.IsNull(yg))
                    {
                        var yt = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
                        if (!Assiweb.IsNull(yt))
                        {
                            yt.usernum = yt.usernum - 1;
                            Db.GetDb().Update(yt);
                        }

                        yg.usernum = yg.usernum - 1;
                        Db.GetDb().Update(yg);
                    }

                }
            }


            return Json(new Jr(1));
        }

        [HttpPost]
        public ActionResult team_user_is()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            var it = Db.GetDb().From<yd_team_out>().Where(a => a.tid == id && a.uid == uid).ToFirst();
            if (it != null)
            {
                return Json(new Jr(21));
            }
            var item = Db.GetDb().From<yd_data>().Where(a => a.tid == id && a.uid == uid).ToFirst();
            return Json(new Jr(item));//判断用户是否已经在团,再团,是否被团给禁止入内了
        }

        [HttpPost]
        public ActionResult team_user_in()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            int gid = Assiweb.GetRequestInt32("gid");//获取看他加入了拿一个团
            int hasgid = Assiweb.GetRequestInt32("hasgid");
            string name = Assiweb.GetRequestString("name");

            //if (hasgid == 1) {
            //    var gr = Db.GetDb().From<yd_group>().Where(a => a.id == gid).ToFirst();
            //    if (Assiweb.IsNull(gr))
            //    {
            //        return Json(new Jr(21));
            //    }
            //}


            var item = Db.GetDb().From<yd_data>().Where(a => a.tid == id && a.uid == uid).ToFirst();
            if (!Assiweb.IsNull(item))
            {
                return Json(new Jr(22));
            }
             

            yd_data yd = new yd_data();
            yd.tid = id;
            yd.uid = uid;
            yd.cdate = DateTime.Now;
            yd.udate = DateTime.Now.Date;
            yd.gid = gid;
            yd.isout = 0;
            yd.step = 0;
            yd.stepday = 0;
            yd.name = name;



            var iday = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate==DateTime.Now.Date).ToFirst();
            if (!Assiweb.IsNull(iday))
            {
                yd.step = iday.step;
                yd.stepday = iday.step;
            }

            Db.GetDb().Insert(yd);

            var t = Db.GetDb().From<yd_team>().Where(a => a.id == id).ToFirst();
            if (t.type == 1 )
            {
                var item2 = new yd_data_js();
                item2.uid = uid;
                item2.tid = t.id;
                item2.startdate = DateTime.Now;
                item2.enddate = DateTime.Now;
                item2.startdura = 0;
                item2.isstart = 0;
                item2.speed = 0;
                item2.second = 0;
                item2.enddura = 0;
                item2.isend = 0;
                item2.credate = DateTime.Now.Date;
                Db.GetDb().Insert(item2);
            }

            if (t.jstype == KqLogic.jstype_10000)
            {
                var item2 = Db.GetDb().From<yd_team_user_his>().Where(a => a.tid == t.id && a.uid == uid && a.type == KqLogic.jstype_10000).ToFirst();
                if (item2 == null)
                {
                    item2 = new yd_team_user_his();
                    item2.tid = t.id;
                    item2.uid = uid;
                    item2.type = KqLogic.jstype_10000;
                    item2.credate = DateTime.Now.Date;
                    Db.GetDb().Insert(item2);
                }
            }

            //判断是否有组,有组 就在组里面进行统计
            int cl = Db.GetDb().From<yd_group>().Where(d => d.tid == yd.tid).Count();
            if (cl == 0)
            {
                var yt = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
                if (!Assiweb.IsNull(yt))
                {

                    yt.usernum = yt.usernum + 1;
                    Db.GetDb().Update(yt);
                    
                        //LogHelper.Error("team_user_in_12_" + item.stepday.ToString() + item.udate.ToString());
                        //这里漏了 即刻添加用户的步数 
                        var ydd = KqLogic.up_user_runday(uid, Convert.ToInt32(yd.stepday), yd.udate, true);
                    //try
                    //{ }
                    //catch (Exception ex)
                    //{
                    //    LogHelper.Error("team_user_in_1_" + ex.ToString());
                    //}

                    KqLogic.SendTm_team_createor(yt);
                }
            }
            


            //var yt = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
            //if (!Assiweb.IsNull(yt))
            //{
            //    yt.usernum = yt.usernum + 1;
            //    Db.GetDb().Update(yt);
            //}

            //var yg = Db.GetDb().From<yd_group>().Where(a => a.id == yd.tid).ToFirst();
            //if (!Assiweb.IsNull(yg))
            //{
            //    yg.usernum = yg.usernum + 1;
            //    Db.GetDb().Update(yg);
            //}


            try
            {
                //发送模板消息 欢迎加入 
                //判断团队是否还未结束
                var yt2 = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
                if (yt2 != null)
                {
                    if (yt2.edate >= DateTime.Now.Date)
                    {
                        if (yt2.jstype == KqLogic.jstype_10000)
                        {
                            KqLogic.SendTm_common_team_tz_join_10000(uid, yd.tid, DateTime.Now.Date.ToString("yyyy年MM月dd日"), "", "");
                        }
                        else
                        {
                            KqLogic.SendTm_common_team_tz(uid, yd.tid, KqLogic.tm_team_userin, "", "");
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("team_user_in_2_" + ex.ToString());
            }
            return Json(new Jr());
        }

        /// <summary>
        /// 团签到
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult team_user_update()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");

            yd_team yt = Db.GetDb().From<yd_team>().Where(a => a.id == id).ToFirst();
            if (Assiweb.IsNull(yt))
            {
                return Json(new Jr(21));
            }

            var item = Db.GetDb().From<yd_data>().Where(a => a.tid == id && a.uid == uid).ToFirst();
            if (Assiweb.IsNull(item))
            {
                return Json(new Jr(22));
            }


            if (yt.bdate.Date <= DateTime.Now.Date && yt.edate.Date >= DateTime.Now.Date)
            {

            }
            else
            {
                return Json(new Jr());
            }
           
            //获取当天的跑步数据,初始化
            //var it2 = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == DateTime.Now.Date).ToFirst();
            //int step = 0;
            //if (!Assiweb.IsNull(it2))
            //{
            //    step = it2.step;
            //    yd_data_team ydt = Db.GetDb().From<yd_data_team>().Where(a => a.tid == id && a.uid == uid && a.udate == DateTime.Now.Date).ToFirst();
            //    if (Assiweb.IsNull(ydt))
            //    {
            //        ydt = new yd_data_team();
            //        ydt.tid = id;
            //        ydt.uid = uid;
            //        ydt.dayid = it2.id;
            //        ydt.udate = DateTime.Now.Date;
            //        Db.GetDb().Insert(ydt);
            //    }
            //}

            //item.stepday = step;//最后一次的提交的步数的数据
            //item.udate = DateTime.Now.Date;
            ////Db.GetDb().Update(item);

            ////统计所有步数的总和
            //string sql = string.Format(@" select sum(b.step) as step from yd_data_team a 
            //                inner join yd_data_day b on a.dayid = b.id 
            //                where a.tid ={0} and a.uid = {1}
            //            ", id.ToString(), uid.ToString());

            //int nbs = Assiweb.GetInt32(Db.GetDb().FromSql(sql).ToScalar().ToString());
            //item.step = nbs;
            //Db.GetDb().Update(item);

            return Json(new Jr());

            //int nbs = Db.GetDb().Sum<yd_data, int>(yd_data_day._.step,);

            //var fs = Db.GetDb().Sum<yd_data_team,int>()
            //    .InnerJoin<yd_data_day>((a, b) => a.dayid == b.id)
            //    .Where(a=>a.tid == id && a.uid == uid)
            //    ;
            //fs.Sum(
            //


        }

        [HttpPost]
        public ActionResult team_close()
        {
            int tid = Assiweb.GetRequestInt32("tid");
            var item = Db.GetDb().From<yd_team>().Where(a => a.id == tid).ToFirst();
            if (item != null)
            {
                item.isclose = 1;
                item.clodate = DateTime.Now;
                Db.GetDb().Update(item);
            }
            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult team_edit()
        {
            string key = Assiweb.GetRequestString("key");
            int uid = Assiweb.GetRequestInt32("uid");

            string fid = Assiweb.GetRequestString("fid");
            if (KqLogic.Check_formid(fid))
            {
                KqLogic.InsTm(uid, fid);
            }


            yd_key yk = null;
            if (Assiweb.StrIsNoEmpty(key))
            {
                ComParam cp = new ComParam();
                cp.Code = key;
                var jr = KqLogic.Check_sqm(cp);
                if (Assiweb.StrIsNoEmpty(jr.message))
                {
                    return Json(jr);
                }
                yk = (yd_key)jr.data;
            }

            int id = Assiweb.GetRequestInt32("id");
            string name = Assiweb.GetRequestString("name");
            int type = Assiweb.GetRequestInt32("type");

            var item = new yd_team();
            if (id > 0)
            {
                item = Db.GetDb().From<yd_team>().Where(a => a.id == id).ToFirst();
                item.udate = DateTime.Now;
            }
            else
            {
                item.cuid = Assiweb.GetRequestInt32("uid");//传贱人
                item.cdate = DateTime.Now;
                item.udate = DateTime.Now;
                item.clodate = DateTime.Now;
                item.isclose = 0;
                item.usernum = 0;
            }

            item.type = type;

            //item.award = Assiweb.GetRequestString("award");
            //item.awardnum = Assiweb.GetRequestInt32("awardnum");
            item.bdate = Assiweb.GetRequestDatetime("bdate");
            item.bjdays = 0; //Assiweb.GetRequestInt32("bjdays");
            //item.cate = Assiweb.GetRequestInt32(yd_team._.cate.TableFieldName);
            
            item.edate = Convert.ToDateTime(Assiweb.GetRequestDatetime("edate").ToString("yyyy-MM-dd") + " 23:59:59");


            item.dura = Assiweb.GetRequestInt32("dura");
            item.zddura = Assiweb.GetRequestInt32("zddura");
            item.qdlat = Assiweb.GetRequestString("qdlat");
            item.qdlng = Assiweb.GetRequestString("qdlng");
            item.qdname = Assiweb.GetRequestString("qdname");
            item.qdaddr = Assiweb.GetRequestString("qdaddr");

            item.zdlat = Assiweb.GetRequestString("zdlat");
            item.zdlng = Assiweb.GetRequestString("zdlng");
            item.zdaddr = Assiweb.GetRequestString("zdaddr");
            item.zdname = Assiweb.GetRequestString("zdname");

            if (item.type == 1 || item.type == 2) {
                //计算距离
                item.diff = Convert.ToInt32(Convert.ToDouble(GetDistance(Convert.ToDouble(item.qdlat), Convert.ToDouble(item.qdlng), Convert.ToDouble(item.zdlat), Convert.ToDouble(item.zdlng))));
            }

            if (item.type == 1)//竞速团
            {
                item.edate = Assiweb.GetRequestDatetime("edate");
            }
            else {
                //步数团是否超过了 90天
                TimeSpan ts = item.edate - item.bdate;
                double dday = ts.TotalDays;
                if (dday > 90) {
                    return Json(new Jr(0));
                }
            }

            if (item.type == 2) {
                item.limithour = Assiweb.GetRequestInt32("limithour");
            }

            //item.issecret = Assiweb.GetRequestInt32("issecret");
            item.key = Assiweb.GetRequestString("key");//如果是开团key
            item.ldate = item.edate;  //Assiweb.GetRequestDatetime("ldate");
            item.name = Assiweb.GetRequestString("name");
            //item.peoples = Assiweb.GetRequestInt32("peoples");

            item.pwd = Assiweb.GetRequestString("pwd");// == n 就是公开团 密码团要6位密码
            if (item.pwd.Length != 6)
            {
                item.pwd = "n";
            }

            item.remark = Assiweb.GetRequestString("remark");
            //item.rules = Assiweb.GetRequestString("rules");
            item.udate = DateTime.Now;

            //item.Attach(Db.GetEs(item.id));
            //Db.GetDb().Save(item);

            if (id > 0)
            {
                Db.GetDb().Update(item);
            }
            else
            {
                item.id = Db.GetDb().Insert(item);
                if (Assiweb.StrIsNoEmpty(key))
                {
                    if (yk != null)
                    {
                        yk.issy = 1;
                        yk.sydate = DateTime.Now;
                        yk.syuid = item.cuid;
                        Db.GetDb().Update(yk);
                    }
                }
            }

            List<yd_group> iyg = new List<yd_group>();

            string group = Assiweb.GetRequestString("group");
            JArray jlist = JArray.Parse(group);

            for (int i = 0; i < jlist.Count; ++i)  //遍历JArray   //这里还没有考虑到多种方式付款,这里比较容易做的
            {
                JObject jb = JObject.Parse(jlist[i].ToString());
                int gid = Assiweb.GetInt32(jb["id"].ToString());
                string gname = jb["name"].ToString();
                if (gid > 0)
                {
                    yd_group yg = Db.GetDb().From<yd_group>().Where(a => a.id == gid).ToFirst();
                    if (yg != null)
                    {
                        yg.name = gname;
                        Db.GetDb().Update(yg);
                        iyg.Add(yg);
                    }
                }
                else
                {
                    yd_group yg = new yd_group();
                    yg.tid = item.id;
                    yg.name = gname;
                    yg.bdate = DateTime.Now;
                    yg.id = Db.GetDb().Insert(yg);
                    iyg.Add(yg);
                }
            }

            if (id == 0)
            {
                //发送模板消息
                string page = "";
                KqLogic.SendTm_team_edit(uid, page,item);
            }

            return Json(new Jr(new { team = item, group = iyg }));
        }


        [HttpPost]
        public ActionResult team_group()
        {
            int id = Assiweb.GetRequestInt32("id");
            var list = Db.GetDb().From<yd_group>().Where(d => d.tid == id).ToList();
            return Json(new Jr(list));
        }

        [HttpPost]
        public ActionResult team_group_Pm()
        {
            
            int id = Assiweb.GetRequestInt32("id");

            string sql = string.Format(@"
                SELECT a.name,b.*,b.step as stepall from 
                yd_group a 
                LEFT JOIN
                (
                    SELECT SUM(step) as step ,count(*) as cc,gid  from yd_data  a
                    where a.tid = {0}
                    GROUP BY gid 
                ) b on b.gid = a.id 
                where a.tid = {0}
                ORDER BY step desc 
            ", id);

            DataTable list = Db.GetDb().FromSql(sql).ToDataTable();
            foreach (DataRow dr in list.Rows) {
                int cc = Assiweb.GetDataRowCol<int>(dr, "cc");
                int step = Assiweb.GetDataRowCol<int>(dr, "step");
                int stepall = Assiweb.GetDataRowCol<int>(dr, "stepall");

                if (cc == 0)
                {
                    dr["step"] = 0;
                    dr["cc"] = 0;
                }
                else {
                    step = Convert.ToInt32(Assiweb.MyDecimalRound((((decimal)step) / cc), 0));
                    dr["step"] = step;
                }
                dr["stepall"] = stepall;
            }
            DataView dv = list.DefaultView;
            dv.Sort = "step desc";
            list = dv.ToTable();

            //for (int i = 0; i < list.Rows.Count; i++)
            //{
            //    if (Assiweb.GetDataRowCol<int>(dt.Rows[i], "gid") == 1314)
            //    {
            //        return i + 1;
            //    }
            //}

            return Json(new Jr(list));
        }


       
        public ActionResult team_user()
        {
            int id = Assiweb.GetRequestInt32("id");
            string tab = Assiweb.GetRequestString("tab");
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;

            if (tab == "1") {
                var result2 = KqLogic.Get_List_Team_User_day(cp);
                return Json(result2);
            }

            var team = Db.GetDb().From<yd_team>().Where(a => a.id == id).ToFirst();

            if (team.type == 1 || team.type == 2) {
                var result3 = KqLogic.Get_List_Team_User_js(cp);
                return Json(result3);
            }
           

            var result = KqLogic.Get_List_Team_User(cp);
            return Json(result);
        }

        public ActionResult team_user_js()
        {
            int id = Assiweb.GetRequestInt32("id");
            string tab = Assiweb.GetRequestString("tab");
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;
           
            var result = KqLogic.Get_List_Team_User_js(cp);
            return Json(result);
        }


        [HttpPost]
        public ActionResult team_pm()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            int gid = Assiweb.GetRequestInt32("gid");
            int tpm = 0;
            int zpm = 0;

            string date = DateTime.Now.ToString("yyyy-MM-dd");

            //计算团排名
            string sql = string.Format(@" 
                        SELECT pm FROM  
                         (  
                             SELECT A.*,@rank:=@rank+1 AS pm  
                             FROM     
                             (    
                              SELECT  uid,step,id FROM yd_data where tid = {0}  and udate = '{2}' ORDER BY stepday DESC ,id asc  
                             ) A ,(SELECT @rank:=0) B   
                         ) M  where m.uid = {1}
                         ORDER BY m.pm
                        ", id.ToString(), uid.ToString(), date);
            var obj = Db.GetDb().FromSql(sql).ToScalar();
            if (obj != null && obj != DBNull.Value) {
                tpm = Assiweb.GetInt32(obj.ToString());
            }
             

            if (gid > 0)
            {
                //计算组排名
                sql = string.Format(@" 
                         SELECT pm FROM  
                          (  
                              SELECT A.*,@rank:=@rank+1 AS pm  
                              FROM     
                              (    
                               SELECT  uid,step,id FROM yd_data where tid = {0} and gid ={2}  and udate = '{3}'  ORDER BY stepday DESC ,id asc  
                              ) A ,(SELECT @rank:=0) B   
                          ) M  where m.uid = {1}
                          ORDER BY m.pm
                         ", id.ToString(), uid.ToString(), gid.ToString(),date);
                 //= Assiweb.GetInt32(Db.GetDb().FromSql(sql).ToScalar().ToString());

                var obj2 = Db.GetDb().FromSql(sql).ToScalar();
                if (obj2 != null && obj2 != DBNull.Value)
                {
                    zpm = Assiweb.GetInt32(obj2.ToString());
                }

            }

            ////获取排名数据
            //int ps = item.awardnum;



            //ComParam cp = new ComParam();
            //cp.ToDatatable = 1;
            //cp.Id = id;
            //cp._PageIndex = 1;
            //cp._PageSize = 1;
            ////如果有组的话
            //var result = KqLogic.Get_List_Team_User_day(cp, uid);
            //zpm = Convert.ToInt32(result.data);


            ////否则获取整组排名
            //var result = KqLogic.Get_List_Team_User_pm(id, uid);
            //pmzd = Convert.ToInt32(result.data);

            return Json(new Jr(new { tpm = tpm, zpm = zpm }));
        }


        [HttpPost]
        public ActionResult team_pm_js()
        {
            int id = Assiweb.GetRequestInt32("id");
            int uid = Assiweb.GetRequestInt32("uid");
            int gid = Assiweb.GetRequestInt32("gid");
            int tpm = 0;
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            //计算团排名
            string sql = string.Format(@" 
                        SELECT pm FROM  
                         (  
                             SELECT A.*,@rank:=@rank+1 AS pm  
                             FROM     
                             (    
                              SELECT  uid ,id FROM yd_data_js where tid = {0} and credate = '{2}'  ORDER BY isend DESC,speed DESC ,isstart DESC ,startdate asc  
                             ) A ,(SELECT @rank:=0) B   
                         ) M  where m.uid = {1}
                         ORDER BY m.pm
                        ", id.ToString(), uid.ToString(), date);

            tpm = Assiweb.GetInt32(Db.GetDb().FromSql(sql).ToScalar().ToString());

            return Json(new Jr(new { tpm = tpm, zpm = 0 }));
        }

        [HttpPost]
        public ActionResult day_pm()
        {
            int uid = Assiweb.GetRequestInt32("uid");

            int dpm = KqLogic.GetDayPm(uid);
             
            return Json(new Jr(new { dpm = dpm }));
        }

        [HttpPost]
        public ActionResult group_user()
        {
            int id = Assiweb.GetRequestInt32("id");
            string tab = Assiweb.GetRequestString("tab");
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;
            int gid = Assiweb.GetRequestInt32("gid");

            if (tab == "1")
            {
                var result2 = KqLogic.Get_List_Group_User_day(cp, gid);
                return Json(result2);
            }

            var result = KqLogic.Get_List_Group_User(cp, gid);
            return Json(result);
        }

        /// <summary>
        /// 用户修改所在组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult group_user_in()
        {
            int id = Assiweb.GetRequestInt32("id");
            int tid = Assiweb.GetRequestInt32("tid");
            int uid = Assiweb.GetRequestInt32("uid");

            var yd = Db.GetDb().From<yd_data>().Where(a => a.uid == uid && a.tid == tid).ToFirst();
            if (!Assiweb.IsNull(yd))
            {
                yd.gid = id;
                Db.GetDb().Update(yd);

                var yt = Db.GetDb().From<yd_team>().Where(a => a.id == yd.tid).ToFirst();
                if (!Assiweb.IsNull(yt))
                {
                    yt.usernum = yt.usernum + 1;
                    Db.GetDb().Update(yt);
                    KqLogic.SendTm_team_createor(yt);
                }

                var yg = Db.GetDb().From<yd_group>().Where(a => a.id == yd.tid).ToFirst();
                if (!Assiweb.IsNull(yg))
                {
                    yg.usernum = yg.usernum + 1;
                    Db.GetDb().Update(yg);
                }
            }

            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult group_user_change()
        {
            int id = Assiweb.GetRequestInt32("id");//新部门
            int gid = Assiweb.GetRequestInt32("gid");//原部门

            int tid = Assiweb.GetRequestInt32("tid");
            int uid = Assiweb.GetRequestInt32("uid");

            //用户替换所在组
            var ydd = Db.GetDb().From<yd_data>().Where(a => a.uid == uid && a.tid == tid).ToFirst();
            ydd.gid = id;
            Db.GetDb().Update(ydd);


            //原来所在组
            var yg = Db.GetDb().From<yd_group>().Where(a => a.id == gid).ToFirst();
            if (!Assiweb.IsNull(yg))
            {
                yg.usernum = yg.usernum - 1;
                Db.GetDb().Update(yg);
            }

            //更新到新的组
            var yg2 = Db.GetDb().From<yd_group>().Where(a => a.id == id).ToFirst();
            if (!Assiweb.IsNull(yg2))
            {
                yg2.usernum = yg2.usernum + 1;
                Db.GetDb().Update(yg2);
            }


            return Json(new Jr());
        }


        [HttpPost]
        public ActionResult group_edit()
        {
            int tid = Assiweb.GetRequestInt32("tid");
            int id = Assiweb.GetRequestInt32("id");
            string name = Assiweb.GetRequestString("name");
            var item = new yd_group();
            if (id > 0)
            {
                item = Db.GetDb().From<yd_group>().Where(a => a.id == id).ToFirst();
            }
            item.tid = tid;
            item.name = name;
            item.bdate = DateTime.Now;

            item.Attach(Db.GetEs(item.id));
            Db.GetDb().Save(item);

            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult group_del()
        {
            int id = Assiweb.GetRequestInt32("id");

            int co = Db.GetDb().From<yd_data>().Where(a => a.gid == id).Count();
            if (co > 0)
            {
                return Json(new Jr(21));
            }

            yd_group yg = Db.GetDb().From<yd_group>().Where(a => a.id == id).ToFirst();
            if (yg != null)
            {
                Db.GetDb().Delete(yg);
            }

            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult user_team()
        {
            int id = Assiweb.GetRequestInt32("uid");//用户id
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;
            cp.Code = Assiweb.GetRequestString("code");
            cp.Date = DateTime.Now.Date;

            var result = KqLogic.Get_List_User_Team(cp);
            return Json(result);

        }

        [HttpPost]
        public ActionResult user_team_admin()
        {
            int id = Assiweb.GetRequestInt32("uid");//用户id
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;
            cp.Code = Assiweb.GetRequestString("code");
           

            var result = KqLogic.Get_List_User_Team_Admin(cp);
            return Json(result);
        }

        [HttpPost]
        public ActionResult user_kb()
        {
            int id = Assiweb.GetRequestInt32("uid");//用户id
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Id = id;

            var result = KqLogic.Get_List_User_Team(cp);
            return Json(result);

        }

        [HttpPost]
        public ActionResult sqm_list()
        {
            string code = Assiweb.GetRequestString("code");
            ComParam cp = new ComParam();
            cp.ToDatatable = 1;
            cp._PageIndex = Assiweb.GetRequestInt32("pageIndex");
            cp._PageSize = Assiweb.GetRequestInt32("pageSize");
            cp.Code = code;

            var result = KqLogic.Get_List_Sqm_admin(cp);
            return Json(result);
        }

        [HttpPost]
        public ActionResult sqm_get_2()
        {
            //生成一个授权码
            int uid = Assiweb.GetRequestInt32("uid");
            yd_key yk = new yd_key();
            yk.cate = "kt";
            yk.issy = 0;
            yk.key = "";
            yk.kuid = uid;
            yk.ldate = Assiweb.GetDatetime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "23:59:59");
            yk.syuid = 0;
            yk.sydate = DateTime.Now;
            Db.GetDb().Insert(yk);

            int id = yk.id;
            int len = 8 - id.ToString().Length;
            string s = KqLogic.GetRandomString(len);
            Db.GetDb().Update<yd_key>(yd_key._.key, s, yd_key._.id == yk.id);

            //验证码跟期限
            return Json(new Jr(new { sqm = s, qx = yk.ldate }));
        }

        [HttpPost]
        public ActionResult sqm_get()
        {
            //生成一个授权码
            int id = Assiweb.GetRequestInt32("id");
            yd_key yk = Db.GetDb().From<yd_key>().Where(a => a.id == id).ToFirst();
            return Json(new Jr(yk));
        }

        [HttpPost]
        public ActionResult sqm_check()
        {
            //生成一个授权码
            string key = Assiweb.GetRequestString("sqm");
            ComParam cp = new ComParam();
            cp.Code = key;
            var jr = KqLogic.Check_sqm(cp);

            return Json(jr);
        }

        [HttpPost]
        public ActionResult sqm_edit()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            int id = Assiweb.GetRequestInt32("id");
            string key = Assiweb.GetRequestString("key");
            DateTime ldate = Assiweb.GetRequestDatetime("ldate");

            var item = new yd_key();
            if (id > 0)
            {
                item = Db.GetDb().From<yd_key>().Where(a => a.id == id).ToFirst();
            }
            else
            {
                item.cate = "kt";
                item.issy = 0;
                item.kuid = uid;
                //item.key = key;
                item.sydate = DateTime.Now;
                item.syuid = 0;
            }

            item.ldate = ldate;

            if (id > 0)
            {
                Db.GetDb().Update(item);
            }
            else
            {
                item.id = Db.GetDb().Insert(item);
                int len = 8 - item.id.ToString().Length;
                string s = item.id.ToString() + KqLogic.GetRandomString(len);
                Db.GetDb().Update<yd_key>(yd_key._.key, s, yd_key._.id == item.id);
                item.key = s;
            }
            return Json(new Jr(item));
        }

        [HttpPost]
        public ActionResult sqm_del()
        {
            int id = Assiweb.GetRequestInt32("id");

            var item = Db.GetDb().From<yd_key>().Where(a => a.id == id).ToFirst();
            if (item.issy == 1) {
                return Json(new Jr(21));
            }
            Db.GetDb().Delete(item);

            return Json(new Jr());
        }

        [HttpPost]
        public ActionResult hyd_user_day()
        {
            //统计所有步数的总和
            string sql = @" SELECT count(uid) as cc,udate from yd_data_day WHERE udate > '2017-10-03'
                                    GROUP BY udate
                                    ORDER BY udate desc 
                                    LIMIT 30
                        ";

            DataTable dt = Db.GetDb().FromSql(sql).ToDataTable();
            return Json(new Jr(dt));
        }

        [HttpPost]
        public ActionResult get_pm25()
        {
            string city = Assiweb.GetRequestString("city");
            string latitude = Assiweb.GetRequestString("latitude");
            string longitude = Assiweb.GetRequestString("longitude");
            int uid = Assiweb.GetRequestInt32("uid");
            string json2 = "";
            try
            {
                string url2 = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&get_poi=1&key=YNSBZ-AGTK3-QHW36-YP6SC-P2MAZ-3EFDL";
                json2 = HttpHelper.Get(url2);
                JObject jb2 = JObject.Parse(json2);
                string status = jb2["status"].ToString();

                string nation = "";
                string province = "";
                string district = "";
                string street = "";
                string street_number = "";


                if (status == "0")
                {
                    city = jb2["result"]["address_component"]["city"].ToString();

                    nation = jb2["result"]["address_component"]["nation"].ToString();
                    province = jb2["result"]["address_component"]["province"].ToString();
                    district = jb2["result"]["address_component"]["district"].ToString();
                    street = jb2["result"]["address_component"]["street"].ToString();
                    street_number = jb2["result"]["address_component"]["street_number"].ToString();
                }

                yd_user_location yul = new yd_user_location();
                yul.city = city;
                yul.credate = DateTime.Now;
                yul.district = district;
                yul.latitude = latitude;
                yul.longitude = longitude;
                yul.nation = nation;
                yul.province = province;
                yul.street = street;
                yul.street_number = street_number;
                yul.type = "wgs84";
                yul.uid = uid;
                Db.GetDbLog().Insert(yul);
               
            }
            catch (Exception ex)
            {
                city = "";
                KqLogic.log("123456_:" + json2 + " " + ex.ToString());

                return Json(new Jr(2));
            }


            //KqLogic.log("city_: " + city);
            if (Assiweb.StrIsNoEmpty(city) && city != "--")
            {
                //读取数据库
                DateTime dt = DateTime.Now.AddHours(-4);
                int hour = DateTime.Now.Hour;
                string json = "";
                //判断是否有数据了
                var item = Db.GetDb().From<yd_pm>().Where(a => a.city == city).OrderByDescending(a => a.id).ToFirst();
                if (item != null)
                {
                    if (item.cre_time < dt)
                    {
                        //4个小时的差额
                    }
                    else
                    {
                       json = item.json;
                    }
                }
                
                //读取接口 获取pm25 的数据
                if (json == "")
                {
                    //string url = "https://way.jd.com/jisuapi/aqi?city=" + city + "&appkey=ac23e03d4ed8124b997caafede930998";


                    string url = "https://way.jd.com/pm25/aqi_by_city?token=5j1znBVAsnSf5xQyNQyq&appkey=ac23e03d4ed8124b997caafede930998&city=" + city.Replace("市", "");


                    
                    try
                    {
                        //KqLogic.log(url);
                        json = HttpHelper.Get(url);
                        yd_pm yp = new yd_pm();
                        yp.city = city;
                        yp.json = json;
                        yp.hour = hour;
                        yp.cre_date = DateTime.Now.Date;
                        yp.cre_time = DateTime.Now;
                        Db.GetDb().Insert(yp);
                    }
                    catch (Exception ex)
                    {
                        json = "";
                        KqLogic.log("https://way.jd.com/jisuapi/aqi_error: " + url + " -- " + ex.ToString());
                    }
                }

                if (Assiweb.StrIsNoEmpty(json))
                {
                    try
                    {
                        JObject jb = JObject.Parse(json);
                        string code = jb["code"].ToString();
                        if (code == "10000")
                        {
                            Newtonsoft.Json.Linq.JArray ja = Newtonsoft.Json.Linq.JArray.Parse(jb["result"].ToString());

                            if (ja != null && ja.Count > 0)
                            {
                                var jg = ja[0];
                                string pm = jg["pm2_5"] != null ? jg["pm2_5"].ToString() : "";
                                string quality = jg["quality"] != null ? jg["quality"].ToString() : "";
                                string measure = "";
                                string affect = "";

                                if (quality == "优")
                                {
                                    measure = "空气这么好，要多出来走走哦！";
                                }
                                else if (quality == "良") {
                                    measure = "空气不错喔，再忙也要记得多运动。";
                                }
                                else if (quality == "轻度污染")
                                {
                                    measure = "敏感人群需要适量减少户外运动。";
                                }
                                else if (quality == "中度污染")
                                {
                                    measure = "可能对心脏、呼吸系统有影响，建议一般人群适量减少户外运动。";
                                }
                                else if (quality == "重度污染")
                                {
                                    measure = "儿童、老年人和心脏病、肺病患者留在室内，停止户外运动，一般人群减少户外运动。";
                                }
                                else if (quality == "严重污染")
                                {
                                    measure = "避免户外活动。";
                                }


                                return Json(new Jr(new { pm = pm, quality = quality, measure = measure, affect = affect, city = city }));

                            }






                            //string pm = jb["result"]["result"]["pm2_5"].ToString();
                            //string quality = jb["result"]["result"]["quality"] != null ? jb["result"]["result"]["quality"].ToString() : "";
                            //string measure = jb["result"]["result"]["aqiinfo"]["measure"] != null ? jb["result"]["result"]["aqiinfo"]["measure"].ToString() : "";
                            //string affect = jb["result"]["result"]["aqiinfo"]["affect"] != null ? jb["result"]["result"]["aqiinfo"]["affect"].ToString() : "";
                            //return Json(new Jr(new { pm = pm, quality = quality, measure = measure, affect = affect,city = city }));
                        }
                    }
                    catch (Exception ex)
                    {
                        json = "";
                        KqLogic.log("https://way.jd.com/jisuapi/aqi_error_json_: " + ex.ToString());
                    }
                }

                return Json(new Jr(2));
            }

            return Json(new Jr(2));
        }

        [HttpPost]
        public ActionResult get_pm25_old()
        {
            string city = Assiweb.GetRequestString("city");
            KqLogic.log("city_: " + city);
            if (Assiweb.StrIsNoEmpty(city) && city !="--") {
                //读取数据库
                DateTime dt = DateTime.Now.Date;
                int hour = DateTime.Now.Hour;
                string json = "";
                //判断是否有数据了
                var item = Db.GetDb().From<yd_pm>().Where(a => a.city == city && a.cre_date == dt && a.hour == hour).ToFirst();
                if (item != null)
                {
                    json = item.json;
                }
                else {
                    //读取接口 获取pm25 的数据

                    string url = "https://way.jd.com/jisuapi/aqi?city=" + city + "&appkey=ac23e03d4ed8124b997caafede930998";
                    try
                    {
                        //KqLogic.log(url);
                        json = HttpHelper.Get(url);
                        yd_pm yp = new yd_pm();
                        yp.city = city;
                        yp.json = json;
                        yp.hour = hour;
                        yp.cre_date = dt;
                        yp.cre_time = DateTime.Now;
                        Db.GetDb().Insert(yp);
                    }
                    catch (Exception ex)
                    {
                        json = "";
                        KqLogic.log("https://way.jd.com/jisuapi/aqi_error: " + url + " -- " + ex.ToString());
                    }
                }

                if (Assiweb.StrIsNoEmpty(json)) {
                    try
                    {
                        JObject jb = JObject.Parse(json);
                        string code = jb["code"].ToString();
                        if (code == "10000")
                        {
                            string pm = jb["result"]["result"]["pm2_5"].ToString();
                            string quality = jb["result"]["result"]["quality"] != null ? jb["result"]["result"]["quality"].ToString() : "";
                            string measure = jb["result"]["result"]["aqiinfo"]["measure"] != null ? jb["result"]["result"]["aqiinfo"]["measure"].ToString() : "";
                            string affect = jb["result"]["result"]["aqiinfo"]["affect"] != null ? jb["result"]["result"]["aqiinfo"]["affect"].ToString() : "";
                            return Json(new Jr(new { pm = pm, quality = quality, measure = measure, affect = affect }));
                        }
                    }
                    catch (Exception ex)
                    {
                        json = "";
                        KqLogic.log("https://way.jd.com/jisuapi/aqi_error_json_: " + ex.ToString());
                    }
                }

                return Json(new Jr(2));
            }

            return Json(new Jr(2));
        }

        public ActionResult SendTmByTimer()
        {
            string type = Assiweb.GetRequestString("type");
            int uid = Assiweb.GetRequestInt32("uid");
            int tid = Assiweb.GetRequestInt32("tid");
            string pm = Assiweb.GetRequestString("pm");
            try
            {
                string page = "";
                if (type == KqLogic.fxjl)//这里感觉没有用 用户获取不到那么多的消息key
                {
                    yd_user yd = Db.GetDb().From<yd_user>().Where(a => a.id == uid).ToFirst();
                    //赠送积分
                    string res = "";//KqLogic.dkjk_user_up_otherkb(yd, tid);
                    if (res == "1")
                    {
                        page = "pages/index/index";
                        pm = "0";//通过接口获取总可用积分
                        //发送模板消息
                        bool bl = KqLogic.SendTm_common_team_tz(uid, tid, type, page, yd.nickname, pm);
                        if (bl == true)
                        {
                            return Content("1");
                        }
                        else
                        {
                            return Content("2");
                        }
                    }
                    else
                    {
                        KqLogic.log("KqLogic.fxjl_ " + res);
                    }
                    return Content("2");
                }
                if (type == "10000") {
                    bool bl = KqLogic.SendTm_common_team_tz_10000(uid, tid, type, page, "", pm);
                    if (bl == true)
                    {
                        return Content("1");
                    }
                    else
                    {
                        return Content("2");
                    }
                }
                else
                {

                    if (type == KqLogic.timer_nodk_time)
                    {
                        page = "pages/index/index";
                        //page = "pages/team/main?tid=" + tid.ToString();
                    }

                    bool bl = KqLogic.SendTm_common_team_tz(uid, tid, type, page, "", pm);
                    if (bl == true)
                    {
                        return Content("1");
                    }
                    else
                    {
                        return Content("2");
                    }
                }
                
            }
            catch (Exception ex)
            {
                KqLogic.log("SendTmByTimer_ " + ex.Message.ToString());
                return Content("0");
            }

        }


        [HttpPost]
        public ActionResult get_yd_dk_txt()
        {
            string type = Assiweb.GetRequestString("type");
            var item =  Db.GetDb().From<yd_dk_txt>().Where(d => d.type == type).ToFirst();
            return Json(new Jr(item));
        }


        public ActionResult save_yd_js()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            int tid = Assiweb.GetRequestInt32("tid");
            int dura = Assiweb.GetRequestInt32("dura");
            int isbegin = Assiweb.GetRequestInt32("isbegin");
            //int type = Assiweb.GetRequestInt32("type");
            //var item = Db.GetDb().From<yd_data_js>().Where(d => d.tid == tid && d.uid == uid).ToFirst();
            //if (type == 2)
            //{
            var item = Db.GetDb().From<yd_data_js>().Where(d => d.tid == tid && d.uid == uid && d.credate == DateTime.Now.Date).ToFirst();
            //}

            if (isbegin == 1) {
                if (item != null)
                {
                    item.startdate = DateTime.Now;
                    item.startdura = dura;
                    item.isstart = 1;
                    Db.GetDb().Update(item);
                }
            }
            else
            {
                if (item != null)
                {
                    item.enddate = DateTime.Now;
                    item.enddura = dura;
                    item.isend = 1;

                    TimeSpan d3 = item.enddate.Subtract(item.startdate).Duration();
                    item.second = (int)d3.TotalSeconds;//花费时间差 秒
                    //计算秒
                    var t = Db.GetDb().From<yd_team>().Where(d => d.id == tid).ToFirst();
                    decimal speed = Assiweb.MyDecimalRound(Convert.ToDecimal(t.diff) / Convert.ToDecimal(item.second), 2);
                    item.speed = speed;
                    Db.GetDb().Update(item);
                }
            }
            return Json(new Jr(item));
        }



        [HttpPost]
        public ActionResult save_user_fx()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            int fxuid = Assiweb.GetRequestInt32("fxuid");
            int tid = Assiweb.GetRequestInt32("tid");
            string type = Assiweb.GetRequestString("type");
            int fxstep = 0;
            KqLogic.log("save_user_fx_1");

            //用户单纯分享获取积分的模式没有实现,这里看看以后怎么做了
            if (tid > 0 && type == "uft")
            {
                //如果在 判断用户是否是新用户
                //如果是 就赠送给步数

                // 新用户是送步数,还是送kb 这个要做一个记录,添加到 yd_user 表里面去.这样就能够做到这个内容了.

                //判断是否足够10000 步, 如果够了 就不用加了. 新用户的关系还是继续保持 
                //做一个共用的方法,如果用户在打卡团里面, 步数足够10000步,那么用户即将进行打卡工作记录
                //连续天数 可以用 方法来计算, 这个计算通过 倒序找天数是否存在.

                //判断用户是否是新用户


                var item = Db.GetDb().From<yd_team_user_his>().Where(a => a.tid == tid && a.uid == uid && a.type == "10000").ToFirst();
                if (item == null)
                {
                    item = new yd_team_user_his();
                    item.tid = tid;
                    item.uid = uid;
                    item.type = "10000";


                    string s = KqLogic.get_sysset_self(KqLogic.fx_step_add).value;
                    try
                    {
                        fxstep = Assiweb.GetInt32(s);
                        //调用签到方法
                    }
                    catch { fxstep = -1; }

                    item.fxuid = fxuid;
                    item.addstep = fxstep;
                    item.credate = DateTime.Now.Date;
                    Db.GetDb().Insert(item);

                    if (fxstep > 0)
                    {
                        //1.判断用户是否在打卡团 打卡团是否仍然开启
                        yd_team yt = Db.GetDb().From<yd_team>().Where(a => a.id == tid).First();
                        if (yt.isclose == 0)
                        {
                            //获取用户今天的步数
                            var ydd = Db.GetDb().From<yd_data_day>().Where(a => a.uid == fxuid && a.udate == DateTime.Now.Date).ToFirst();
                            if (ydd != null)
                            {
                                fxstep = Convert.ToInt32(ydd.step) + fxstep;
                            }
                        }
                        KqLogic.up_user_runday(fxuid, fxstep, DateTime.Now.Date);
                        Get_Team_Qd(fxuid);
                    }

                }
                return Json(new Jr(1));
            }

            int isnew = Assiweb.GetRequestInt32("isnew");
            KqLogic.log("save_user_fx_2_" + isnew.ToString());//&& isnew == 1
            if (type == "u_f" )
            {
                KqLogic.log("save_user_fx_3_");
                yd_user yd = Db.GetDb().From<yd_user>().Where(a => a.id == uid).ToFirst();
                if (yd != null && yd.fxuid == 0)
                {
                    KqLogic.log("save_user_fx_4_");
                    string city = "";
                    var latitude = Assiweb.GetRequestString("latitude");
                    var longitude = Assiweb.GetRequestString("longitude");

                    string url2 = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&get_poi=1&key=YNSBZ-AGTK3-QHW36-YP6SC-P2MAZ-3EFDL";
                    string json2 = HttpHelper.Get(url2);
                    JObject jb2 = JObject.Parse(json2);
                    string status = jb2["status"].ToString();

                    string nation = "";
                    string province = "";
                    string district = "";
                    string street = "";
                    string street_number = "";


                    if (status == "0")
                    {
                        city = jb2["result"]["address_component"]["city"].ToString();

                        nation = jb2["result"]["address_component"]["nation"].ToString();
                        province = jb2["result"]["address_component"]["province"].ToString();
                        district = jb2["result"]["address_component"]["district"].ToString();
                        street = jb2["result"]["address_component"]["street"].ToString();
                        street_number = jb2["result"]["address_component"]["street_number"].ToString();
                    }

                    yd_user_location_fx yul_fx = new yd_user_location_fx();
                    yul_fx.city = city;
                    yul_fx.credate = DateTime.Now;
                    yul_fx.district = district;
                    yul_fx.latitude = latitude;
                    yul_fx.longitude = longitude;
                    yul_fx.nation = nation;
                    yul_fx.province = province;
                    yul_fx.street = street;
                    yul_fx.street_number = street_number;
                    yul_fx.type = "wgs84";
                    yul_fx.uid = uid;
                    yul_fx.fxuid = fxuid;
                    Db.GetDb().Insert(yul_fx);
                    KqLogic.log("save_user_fx_5_");
                    //string s = KqLogic.get_sysset_self(KqLogic.fxjl).value;
                    //try
                    //{
                    //    fxstep = Assiweb.GetInt32(s);
                    //    if (fxstep > 0)
                    //    {
                    //        yd_user yu = KqLogic.get_user(fxuid);
                    //        调用接口送积分
                    //        string res = KqLogic.dkjk_user_up_otherkb(yu, fxstep, "分享奖励");
                    //        if (res == "1")
                    //        {
                    //            积分赠送成功
                    //            fxstep = -1;
                    //        }
                    //    }
                    //}
                    //catch { }

                    yd.fxuid = fxuid;
                    yd.fxdate = DateTime.Now.Date;
                    yd.fxtime = DateTime.Now;
                    yd.fxtype = type;
                    yd.fxvalue = fxstep.ToString();
                    yd.latitude = latitude;
                    yd.longitude = longitude;

                    Db.GetDb().Update(yd);
                    return Json(new Jr(1));
                }
            }

            return Json(new Jr(1));
        }

        public void Get_Team_Qd(int uid)
        {
            //判断当前步数是否超过需要值
            //获取签到信息
            
            string s = KqLogic.get_sysset_self(KqLogic.fxstep_10000).value;
            int fxstep = Assiweb.GetInt32(s);

            var ydd = Db.GetDb().From<yd_data_day>().Where(a => a.uid == uid && a.udate == DateTime.Now.Date).ToFirst();
            //大于10000 在签到
            if (ydd.step > fxstep)
            {
                //获取用户所在的team 是 
                var where = new Where<yd_team>();
                where.And<yd_data>((a, b) => b.uid == uid && a.isclose == 0 && a.edate >= DateTime.Now.Date && a.bdate <= DateTime.Now.Date && a.jstype == KqLogic.jstype_10000);

                var el_data = Db.GetDb().From<yd_team>()
                               .Select(yd_team._.All)
                               .InnerJoin<yd_data>((a, b) => a.id == b.tid)
                               .Where(where)
                               .ToList();
                DateTime dtn = DateTime.Now.Date;
                //开始操作签到
                foreach (yd_team it in el_data)
                {
                    //添加签到数据
                    var item = Db.GetDb().From<yd_data_qd>().Where(a => a.uid == uid && a.tid == it.id && a.credate == dtn.Date && a.type == KqLogic.jstype_10000).ToFirst();
                    if (item == null)
                    {
                        var old = Db.GetDb().From<yd_data_qd>().Where(a => a.uid == uid && a.tid == it.id && a.credate == dtn.Date.AddDays(-1) && a.type == KqLogic.jstype_10000 && a.dqqd < KqLogic.qdday_10).ToFirst();

                        item = new yd_data_qd();
                        item.uid = uid;
                        item.tid = it.id;
                        item.credate = dtn.Date;
                        item.type = KqLogic.jstype_10000;
                        item.step = ydd.step;

                        if (old == null)
                        {
                            item.dqqd = 1;
                        }
                        else
                        {
                            item.dqqd = old.dqqd + 1;
                        }

                        if (item.dqqd == KqLogic.qdday_10) {
                            item.qdlj = 1;
                        }

                        Db.GetDb().Insert(item);

                        //这里应该判断昨天是否是正常签到的 这样可以直接统计签到

                    }
                }
            }
        }

        public ActionResult get_user_qd_list()
        {
            string code = Assiweb.GetRequestString("code");
            int tid = Assiweb.GetRequestInt32("tid");
            if (string.IsNullOrWhiteSpace(code))
            {
                var ls = new List<yd_data_qd>();
                return Json(new Jr(true, ls, "", 0));
            }

            yd_user yu = Db.GetDb().From<yd_user>().Where(a => a.code == code || a.phone == code).ToFirst();
            if (yu == null)
            {
                var ls = new List<yd_data_qd>();
                return Json(new Jr(true, ls, "", 0));
            }

            //获取用户在该team下面的签到列表
            //var list = Db.GetDb().From<yd_data_qd>().Where(a => a.tid == tid && a.qdlj > 0 && a.uid == yu.id).ToList();&& ( a.credate >= DateTime.Now.Date.AddDays(-10) || a.qdlj >0 )

            var list = Db.GetDb().From<yd_data_qd>().Where(a => a.tid == tid && a.uid == yu.id  ).OrderByDescending(a => a.credate).ToList();

            return Json(new Jr(true, list, "", list.Count));
        }

        public ActionResult get_user_qdlj()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            int qdid = Assiweb.GetRequestInt32("qdid");

            //获取用户在该team下面的签到列表
            var item = Db.GetDb().From<yd_data_qd>().Where(a => a.id == qdid).ToFirst();
            item.qdlj = 2;
            item.lddate = DateTime.Now;
            Db.GetDb().Update(item);
            return Json(new Jr(1));
        }

        public ActionResult add_cardmax()
        {
            int maxc = 10000;
            var list = Db.GetDb().From<yd_user>().ToList();
            foreach (yd_user yu in list) {
                yu.code = GetCardMax_init(ref maxc);
            }
            Db.GetDb().Update(list);
            return Json(new Jr(1));
        }

        public string GetCardMax() {
            yd_cardmax yc = Db.GetDb().From<yd_cardmax>().Where(a => a.id == 1).ToFirst();
            string str = (yc.cardmax + 1).ToString();
            char[] sz = str.ToCharArray();
            for (int i = 0; i < sz.Length; i++)
            {
                if (sz[i].ToString() == "4" || sz[i].ToString() == "7")
                {
                    sz[i] = Convert.ToChar((Convert.ToInt32(sz[i].ToString()) + 1).ToString());
                }
            }
            str = new string(sz);
            yc.cardmax = Convert.ToInt32(str);
            Db.GetDb().Update(yc);
            return str;
        }

        public string GetCardMax_init(ref int maxc)
        {
            string str = (maxc + 1).ToString();
            char[] sz = str.ToCharArray();
            for (int i = 0; i < sz.Length; i++)
            {
                if (sz[i].ToString() == "4" || sz[i].ToString() == "7")
                {
                    sz[i] = Convert.ToChar((Convert.ToInt32(sz[i].ToString()) + 1).ToString());
                }
            }
            str = new string(sz);
            maxc = Convert.ToInt32(str);
            return str;
        }


        private const double EARTH_RADIUS = 6378.137;//地球半径
        private static double rad(double d)
        {
            return d * Math.PI / 180.0;
        }

        public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
        {
            double radLat1 = rad(lat1);
            double radLat2 = rad(lat2);
            double a = radLat1 - radLat2;
            double b = rad(lng1) - rad(lng2);

            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
             Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            s = s * 1000;
            return s;
        }


        public ActionResult get_advertise()
        {
            int uid = Assiweb.GetRequestInt32("uid");
            //目前只能有一个广告是激活的,不能搞多广告

            var item = Db.GetDb().From<yd_advertise>().Where(a => a.is_del == 0).First();
            if (item != null)
            {
                //判断用户是否参与了
                var ui = Db.GetDb().From<yd_advertise_user>().Where(a => a.uid == uid && a.aid == item.id).First();
                if (ui == null)
                {
                    //表示用户没有点击过该广告 需要弹出给用户看
                    item.imgurl = "https://app.dkcake.com" + item.imgurl;
                    return Json(new Jr(item));
                }
            }
            return Json(new Jr(1));
        }

        public ActionResult get_advertise_add() {
            int uid = Assiweb.GetRequestInt32("uid");
            int aid = Assiweb.GetRequestInt32("aid");
            int isok = Assiweb.GetRequestInt32("isok");

            yd_advertise_user yau = new yd_advertise_user();
            yau.aid = aid;
            yau.uid = uid;
            yau.num =1;
            yau.create_date = DateTime.Now;
            yau.isok = isok;
            Db.GetDb().Insert(yau);

            return Json(new Jr(1));
        }

    }
}
 